Copy entire contents of a directory and preserve permissions

Contributor Icon Contributed by nifran Date Icon July 15, 2004  
Tag Icon Tagged: Solaris

Sometimes it’s needed to move the contents of a directory to another mount point, or even another system using tar.

tar preserves permissions on files better than other methods of copying.


To move on the same system, do the following:

cd dir1 && tar -cf – . | (cd dir2 && tar -xpvf -)

dir1 is the directory you want to copy
dir 2 is the directory you want the copy to go into.

This tar’s the current directory to STDOUT, then changes directory and untar’s the archive without ever having to find the space for a .tar file.

You can also do this across systems via ssh:
cd dir1 && tar -cf – . | ssh system2 “cd dir2 && tar -xpvf -”

Previous recipe | Next recipe |
 
  • fall-line
    what's wrong with cp -Rp dir1 dir2 ?
  • Anonymous
    'cp -Rp' is not supported on most Unixes. '-Rp' flags are only supported by the version of 'ls' that comes with the GNU Core-utils, which is not installed everywhere.

    The tar command will work on all versions of Unix.
  • Anonymous
    In addition, I think you meant 'cp -a', which is equivilant to 'cp -dpR'. The -d flag will dereference symbolic links.

    'cp -Rp dir1 dir2' doesn't preserve symlinks. It will instead copy the contents of the target:


    If dir1 looks like this:


    -rw-r--r-- 1 flarg group 0 Aug 17 14:59 file1
    lrwxrwxrwx 1 flarg group 4 Aug 17 14:59 link1 -> /tmp



    If you use 'cp -Rp', then 'link1' will become a directory:


    cp -Rp dir1 dir2
    -rw-r--r-- 1 flarg group 0 Aug 17 14:59 file1
    drwxrwxrwx 7 flarg groupl 1701 Aug 17 14:59 link1



    You really want the '-d' flag to dereference any symbolic links.
  • Anonymous
    <ul id="quote">
    flarg wrote:
    In addition, I think you meant 'cp -a', which is equivilant to 'cp -dpR'. The -d flag will dereference symbolic links.

    'cp -Rp dir1 dir2' doesn't preserve symlinks. It will instead copy the contents of the target:


    If dir1 looks like this:


    -rw-r--r-- 1 flarg group 0 Aug 17 14:59 file1
    lrwxrwxrwx 1 flarg group 4 Aug 17 14:59 link1 -> /tmp



    If you use 'cp -Rp', then 'link1' will become a directory:


    cp -Rp dir1 dir2
    -rw-r--r-- 1 flarg group 0 Aug 17 14:59 file1
    drwxrwxrwx 7 flarg groupl 1701 Aug 17 14:59 link1



    You really want the '-d' flag to dereference any symbolic links.</ul>
  • joppe Koning
    cp uses a caracter for caracter copy method. copying with tar is faster because is uses greater buffers
  • trwww
    Your command copy / pastes from FF 3.5 to MindTerm on windows XP as:

    cd dir1 && tar -cf ? . | (cd dir2 && tar -xpvf -)

    Note the ? instead of the -

    I was in my user's home directory at the time so its all gone now! Whee!
  • shreyash
    nice work dude......i like all solaris recipes.......i appreciate ur work......
blog comments powered by Disqus