tar method of recursive file copying

30 Jan 2009
Posted by luciferous
luciferous's picture

I heard that recursive copying using tar and stdin is faster than cp -R. The syntax to do so is a little awkward. Here is an example which is the equivalent of cp -R source destination:

~$ mkdir destination
~$ cd source
~/source$ tar cf - . | (cd ../destination; tar xf -)

I have created a convenient script (cpr) which uses the tar method but whose syntax is closer to the cp method. The same example as above with the script:

~$ cpr source destination

What if we want to copy just the files inside source and put them in the current director? cpr differentiates between source and source\ – note the backslash – so we write:

~$ cpr source/ .

Anyway, this was just an exercise out of curiosity. And the end of the day, it does nothing more than what cp could do, but I got a refresher on bash string manipulation. Maybe this is interesting to somebody.

#!/bin/sh

[ ! ${#@} -eq 2 ] && echo "usage: $0 <source> <destination>" && exit 1

SRC=$1
DEST=`expr $2 : '\(.*\)/*'`
DIR=`expr //$1 : '.*/\(.*\)'`

[ $DEST == '.' ] && DEST="$DEST/$DIR"

[ ! -e $SRC ] && echo "Source directory doesn't exist" && exit 2
if [ ! -e $DEST/$DIR ]; then
  mkdir $DEST
  [ $? -gt 0 ] && echo "Could not create destination directory" && exit 3
fi

(cd $SRC; tar cf - ./)|(cd $DEST; tar xf -)