Copying directories

Both cpio and tar may be used to copy directories while preserving ownership, permissions, and directory structure.

cpio example:
cd fromdir
find . | cpio -pdumv todir

tar example:
cd fromdir; tar cf - . | (cd todir; tar xfp -)

tar example over a compressed ssh tunnel:
tar cvf - fromdir | gzip -9c | ssh user@host 'cd todir; gzip -cd | tar xpf -'

Example:

After performing a Live Upgrade to Solaris 8 from Solaris 7 on a system, the /usr file system was 99% full. The /opt file system has plenty of free space, so I will move at least one subdirectory from /usr to /opt, and create a symbolic link to the new location.

$ df -k /usr /opt
Filesystem            kbytes    used   avail capacity  Mounted on
/dev/dsk/c3t0d0s5    1018382  942235   15045    99%    /usr
/dev/dsk/c3t0d0s6    1755415  941324  761429    56%    /opt

1. Determine 5 largest subdirectories in /usr:

$ cd /usr

$ du -sk * | sort -n | tail -5
51896   share
55420   atria
115693  dt
160576  lib
261558  openwin

2. Determine if /usr/openwin is in use by system processes with lsof.

$ lsof +D /usr/openwin

xfs       28852  nobody  txt   VREG 118,149   276952 245019 /usr/openwin/bin/xfs
xfs       28852  nobody  txt   VREG 118,149   176724  33988 /usr/openwin/server/lib/libtypesclr.so.0
xfs       28852  nobody  txt   VREG 118,149   493352  34448 /usr/openwin/server/lib/libfont.so.1
rpc.ttdbs 29122    root  txt   VREG 118,149   288352 244540 /usr/openwin/bin/rpc.ttdbserverd
rpc.ttdbs 29122    root  txt   VREG 118,149   709492  68957 /usr/openwin/lib/libtt.so.2

Ideally, you would only want to move directories that are not in use by system processes. I will proceed with moving /usr/openwin in this case.

3. Use cpio to copy the directory while preserving ownership, permissions, and directory structure.

mkdir /opt/openwin

cd /usr/openwin
find . | cpio -pdumv /opt/openwin
find /usr/openwin | cpio -pdumv /opt/openwin

4. Rename /usr/openwin and create a symbolic link to /opt/openwin.
mv /usr/openwin /usr/openwin_to_be_removed; ln -s /opt/openwin /usr/openwin

5. Remove the  backup copy of /usr/openwin to free up the space.
rm -rf /usr/openwin_to_be_removed

More information:
Copying Directory Trees

Back to brandonhutchinson.com.
Last modified: 2007/06/13