Main Content

Copying files and preserving ownership

Archive - Originally posted on "The Horse's Mouth" - 2006-04-28 08:53:01 - Graham Ellis

If you're copying a file on a Unix / Linux / OS X operating system, use the cp command. Use cp -r to copy a directory and all its contents - the -r means "recursive". If you use the cp command to copy files that you have read access to, but do not own, then you'll be made the owner of the new copies; for the command to do otherwise would have security implications.

So what if you need to copy whole directory structure and retain the current user and group assignments? First, you'll need to log in as the system administrator (root). Use the su - command and be careful!

Once you're logged in as root, change to the directory that's above the one you wish to copy, and copy via the tar command. For example, to copy everything in /home to /second/home:

cd /
mkdir /second
tar cpf - home | (cd second; tar xpf -)


The tar utility is more often used to make an archive file containing all of the information in a directory or series of directorys.

• Specified with the c parameter, tar creates an archive and with the x parameter, it extracts from an archive

• With the f - option, tar is instructed to write to stdout or read from stdin.

• The p option preserves ownerships on extraction, to prevent all of the files being changed to the ownership of the person running the command ... and for reasons of inter-user security, this only works for root.