UNIX How to copy entire directory (subdirectories and files) from one location to another and retain permissions

H. Ferrence picture H. Ferrence · Oct 1, 2014 · Viewed 20.7k times · Source

I just copied an entire directory structure from one location on my server to another:

cp -r /home/abc/public_html/* /home/xyz/public_html/

That worked fine. Except the dirs & files are now owned by root and the group is root as well.

How do I perform this copy action and retain the dirs & files ownership, groups, and permission settings?

Here is my man cp

NAME
       cp - copy files and directories

SYNOPSIS
       cp [OPTION]... [-T] SOURCE DEST
       cp [OPTION]... SOURCE... DIRECTORY
       cp [OPTION]... -t DIRECTORY SOURCE...

DESCRIPTION
       Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

       Mandatory arguments to long options are mandatory for short options too.

       -a, --archive
              same as -dR --preserve=all

       --backup[=CONTROL]
              make a backup of each existing destination file

       -b     like --backup but does not accept an argument

       --copy-contents
              copy contents of special files when recursive

       -d     same as --no-dereference --preserve=links

       -f, --force
              if an existing destination file cannot be opened, remove it and try again (redundant if the -n option is used)

       -i, --interactive
              prompt before overwrite (overrides a previous -n option)

       -H     follow command-line symbolic links in SOURCE

       -l, --link
              link files instead of copying

       -L, --dereference
              always follow symbolic links in SOURCE

       -n, --no-clobber
              do not overwrite an existing file (overrides a previous -i option)

       -P, --no-dereference
              never follow symbolic links in SOURCE

       -p     same as --preserve=mode,ownership,timestamps

       --preserve[=ATTR_LIST]

Answer

Joakim Nohlgård picture Joakim Nohlgård · Oct 1, 2014

Use cp -a to copy permissions and user/group.

The man page explains it:

-a, --archive
    same as -dR --preserve=all
...
-d     same as --no-dereference --preserve=links
...
-R, -r, --recursive
   copy directories recursively
...
--preserve[=ATTR_LIST]
   preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes:
   context, links, xattr, all