How do I copy a folder keeping owners and permissions intact?

So I was going to back up my home folder by copying it to an external drive as follows:

sudo cp -r /home/my_home /media/backup/my_home

With the result that all folders on the external drives are now owned by root:root. How can I have cp keep the ownership and permissions from the original?


Solution 1:

Use the -p flag.

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

--preserve[=ATTR_LIST]
       preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: context, links, xattr, all

Note that for the permissions to be correctly replicated, the destination file system should be the same as the source file system. In other words, your external drive should be formatted as ext4 if, as is usually the case, your home folder is stored on a partition of that type.

Solution 2:

You can use the -p flag:
cp -rp /home/my_home /media/backup/my_home
or use rsync command line:
rsync -aux /home/my_home /media/backup/my_home

Solution 3:

Use sudo cp -a /home/my_home /media/backup/my_home, it will recurse into subdirs and preserve all file attributes.

Solution 4:

Older answers above would put the folder 'my_home' into the my_home folder on the destination resulting in /media/backup/my_home/my_home/child_stuff

so this might be better:

sudo cp -a /home/my_home/. /media/backup/my_home

the '/.' on the source copies the contents and includes hidden files.