Recipe: How to copy files and directories recursively with tar

TAR is the Unix Tape ARchive utility. It can be used to either store data on a streaming tape device like a DAT drive, or store files in what is commonly called a tarball file - somewhat like a pkzip file, only compression is optional.

Copying a directory tree and its contents to another filesystem using tar will preserve ownership, permissions, and timestamps. A neat trick allows using tar to perform a recursive copy without creating an intermediate tar file.

To copy all of the files and subdirectories in the current working directory to the directory /target, use:

tar cf - * | ( cd /target; tar xfp - )

The first part of the command before the pipe instruct tar to create an archive of everything in the current directory and write it to standard output (the - in place of a filename frequently indicates stdout).

The commands within parentheses cause the shell to change directory to the target directory and untar data from standard input. Since the cd and tar commands are contained within parentheses, their actions are performed together.

The -p option in the tar extraction command directs tar to preserve permission and ownership information, if possible given the user executing the command (if you are running the command as superuser, this option is turned on by default and can be omitted.)

Just a reminder, to tar a given directory(ies) with all subdirectories and files, recursively, to a tar file in the current directory:

tar cf backup.tar /path/to/directory1 /path/to/directory2

example:

tar cf backup.tar /www /etc /var /usr/local/etc /boot/*.conf

That'll include all those directory (recursively, with hidden files) to backup.tar in the current directory. I added /boot/*.conf as an example of when shell globbing is required.

After that, look at what is in your archive:

tar tf backup.tar | less

-C

tar cf - * | tar xf - -C /path/to/target/directory

Thank you.

Thank you.

Post new comment

The content of this field is kept private and will not be shown publicly.