User Tools

Site Tools


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
# - 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.
find $sourceDir -name "$fileMask" -print | \
while read file
     # ensure that dir exists then copy file
     mkdir -p $destDir/`dirname "$file"`
     cp  "$file"  $destDir/$file
/home/cfreyer/public_html/data/pages/technology/linux/recursivecopy.txt · Last modified: 2009/01/26 14:56 by Chris Freyer