Wednesday, November 19, 2014

Shell Script To Delete Files In The First Directory Which Are Similarly Named In The Second Directory

A shell script to compare files in two directory and delete files in the first directory which are similarly named in the second directory. Following script uses for loop to compare files in a each directory.
  1. #!/bin/bash
  2. # Write a shell script that accepts two directory names as arguments and
  3. # deletes those files in the first directory which are similarly named in
  4. # the second directory.
  5. SRC="$1"
  6. DST="$2"
  7. if [ $# -ne 2 ]
  8. then
  9. echo "$(basename $0) dir1 dir2"
  10. exit 1
  11. fi
  12.  
  13. if [ ! -d $SRC ]
  14. then
  15. echo "Directory $SRC does not exists!"
  16. exit 2
  17. fi
  18.  
  19.  
  20. if [ ! -d $DST ]
  21. then
  22. echo "Directory $DST does not exists!"
  23. exit 2
  24. fi
  25.  
  26. for f in $DST/*
  27. do
  28. #echo Processing $f
  29. if [ -f $f ]
  30. then
  31. tFile="$SRC/$(basename $f)"
  32. if [ -f $tFile ]
  33. then
  34. echo -n "Deleting $tFile..."
  35. /bin/rm $tFile
  36. [ $? -eq 0 ] && echo "done" || echo "failed"
  37.  
  38. fi
  39. fi
  40. done

0 comments: