Skip to content

Copying a directory tree in Unix or Linux

cd to the parent of the source directoryUse the following command:

tar -cf - sourcedir | "cd destdirparent && tar -xf -"

where:
sourcedir is the directory to copy
destdirparent is the parent directory to copy the directory to

The -f - option tells tar to write the archive to stdout or read the archive from stdin as the case may be.

Placing the command after the pipe in quotes causes it to run in a subshell. This means that the two halves to the command can operate in different directories. The && means that if the cd command fails the tar won’t run either.

For example:

cd /home/fred
tar -cf - Maildir | "cd /d02/backup/fred && tar -xf -"

Note also that the source directory could be the current directory.

2 Comments

  1. Andrew S wrote:

    “Note also that the source directory could be the current directory.”

    The results from doing this could be interesting…

    Tuesday, December 4, 2007 at 9:37 pm | Permalink
  2. Andrew S wrote:

    Depending on the OS and circumstances I tend to use either cpio:

    sudo find /home/fred | sudo cpio -pmduV /d02/home

    or rsync:

    sudo rsync -vaPHx /home/fred /d02/home/

    The latter will preserve hardlinks.

    Tuesday, December 4, 2007 at 9:40 pm | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*