Alternate to CP

Here is one of those tips that will let you do a recursive copy of a directory to another location using tar. By using tar and not cp, it will preserve the PERMISSIONS and OWNERSHIPS of all the files it touches.

Simply “cd” to the source location and execute the following command:

tar cvf - . | ( cd /path/to/destination/ ; tar xvf - )

(the commands inside the parentheses get executed in a sub-shell therefore parentheses are also required)

That can also be written as:

tar cvf - . | tar -C /path/to/destination/ xvf -

Another popular method is to use “find” and cpio:

find /old/dir -depth -a -print | cpio -pdumv /new/dir

Thats it!

For even an even easier operation, you can create an alias in your .bashrc file (assuming that you are using bash as your shell of course). Enter this in your .bashrc file:

alias cpbytar='tar cvf - . | ( cd $1 ; tar xvf - )'

Source the .bashrc file, “cd” into the directory you wish to copy then run:

cpbytar destination_directory

That will tar'up and move all the files in the current working directory you might be in to the destination directory that you entered.

All your copied files will keep the same, permissions, ownerships and time stamps. Enjoy!

About this entry