sinisterstuf

copy-non-empty

Oct 25th, 2011
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.60 KB | None | 0 0
  1. #!/bin/bash
  2. #this script copies non-empty directories (folders) to another directory
  3.  
  4. #flag for executing the search loop, yes by default
  5. dome=1
  6. #counters to show stats at the end
  7. emptycount=0
  8. fullcount=0
  9. errcount=0
  10.  
  11. #set the source and destination for copying
  12. if [[ $# = 0 || $1 = '-h' ]]
  13. then
  14.     dome=0
  15.     echo "this script copies non-empty directories (folders) to another directory"
  16.     echo "it requires 1 or 2 argument:"
  17.     echo " copy-non-empty.sh [source] destination"
  18.     echo "if the source is not specified, the current directory is searched"
  19.     echo
  20. elif [[ $# = 1 ]]
  21. then
  22.     dest=$1
  23.     src=`pwd`
  24.     echo -n "copying from" $src "to" $dest "proceed [Y/n]? "
  25.     read selection
  26.     if [[ ${selection,,} = n ]]
  27.     then
  28.         dome=0
  29.     fi
  30. elif [[ $# -gt 1 ]]
  31. then
  32.     dest=$2
  33.     src=$1
  34.     echo -n "copying from" $src "to" $dest "proceed [Y/n]? "
  35.     read selection
  36.     if [[ ${selection,,} = n ]]
  37.     then
  38.         dome=0
  39.     fi
  40. fi
  41.  
  42.  
  43. #the actual loop
  44. if [[ $dome = 1 ]]
  45. then
  46.     for folder in `ls $src`
  47.     do
  48.         if [[ -d $src/$folder && `ls $src/$folder | wc -l` -gt 0 ]]
  49.         then
  50.             echo -n $src/$folder 'is not empty, copying... '
  51.             cp -r $src/$folder $dest
  52.             #check for success on copying
  53.             if [[ $? = 0 ]]
  54.             then
  55.                 fullcount=$(expr $fullcount + 1)
  56.                 echo 'copied'
  57.             else
  58.                 errcount=$(expr $errcount + 1)
  59.                 echo 'failed'
  60.             fi
  61.         else
  62.             echo $src/$folder 'is empty, skipping'
  63.             emptycount=$(expr $emptycount + 1)
  64.         fi
  65.     done
  66. fi
  67.  
  68. #print stats
  69. echo -n "done:" $fullcount "directories copied and" $emptycount "empty directories skipped"
  70. if [[ $errcount -gt 0 ]]
  71. then
  72.     echo " and" $errcount "errors"
  73. else
  74.     echo
  75. fi
  76.  
  77.  
Advertisement
Add Comment
Please, Sign In to add comment