Skip to content

Selective Recursive Copy Script

I had a need to copy certain files from one directory to another. Not all the files, just some that I could identify by file extension. Unfortunately the recursive copy command on Linux (i.e. cp -r) doesn't like selective commands like this one:

  cp -r sourceDir/*.properties destDir

Apparently, specifying a filename instead of a directory causes cp not to create the directory structure on the destination side, so the command fails:

  [root@cvgws901 temp]# cp -r sourceDir/*.properties backup
  cp: cannot stat `sourceDir/*.prop': No such file or directory

I'm sure I could have researched this and found a more elegant solution (like possibly the right params for find, xargs, and cp. But sometimes its more important to be done than to be elegant. This is one of those times. :-) I wrote this script in about 5 minutes and have used it several times already. Enjoy.

#! /bin/bash -x
#
# cps.sh - copy selective
# Chris Freyer 1/26/2009
#
# Selectively finds files (fileMask)  located
# in the source directory (sourceDir) and copies them
# to the destination directory (destDir), reproducting the structure
# while copying.

sourceDir=myproject
destDir=backup
fileMask=*.properties

find $sourceDir -name "$fileMask" -print | \
while read file
do
     # ensure that dir exists then copy file
     mkdir -p $destDir/`dirname "$file"`
     cp  "$file"  $destDir/$file
done