cmptree 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #!/bin/bash
  2. #cmptree: compare directory trees recursively and report the differences.
  3. #this script from: http://www.drdobbs.com/the-shell-corner-cmptree/199103123
  4. #written by Ives Aerts, February 2001.
  5. #Executing the following: cmptree /tmp/dir1 /tmp/dir2
  6. #performs a valid search, but executing: cmptree linkdir1 linkdir2
  7. #displays a "different link targets" message.
  8. export LANG=C
  9. function gettype () {
  10. if [ -L $1 ]; then
  11. echo "softlink"
  12. elif [ -f $1 ]; then
  13. echo "file"
  14. elif [ -d $1 ]; then
  15. echo "directory"
  16. else
  17. echo "unknown"
  18. fi
  19. }
  20. function exists () {
  21. if [ -e $1 -o -L $1 ]; then
  22. return 0;
  23. else
  24. echo "$1 does not exist."
  25. return 1;
  26. fi
  27. }
  28. function comparefile () {
  29. cmp -s $1 $2
  30. if [ $? -gt 0 ]; then
  31. echo "$1 different from $2"
  32. # else
  33. # echo "$1 same as $2"
  34. fi
  35. return
  36. }
  37. function comparedirectory () {
  38. local result=0
  39. for i in `(ls -A $1 && ls -A $2) | sort | uniq`; do
  40. compare $1/$i $2/$i || result=1
  41. done
  42. return $result
  43. }
  44. function comparesoftlink () {
  45. local dest1=`ls -l $1 | awk '{ print $11 }'`
  46. local dest2=`ls -l $2 | awk '{ print $11 }'`
  47. if [ $dest1 = $dest2 ]; then
  48. return 0
  49. else
  50. echo "different link targets $1 -> $dest1, $2 -> $dest2"
  51. return 1
  52. fi
  53. }
  54. # compare a file, directory, or softlink
  55. function compare () {
  56. (exists $1 && exists $2) || return 1;
  57. local type1=$(gettype $1)
  58. local type2=$(gettype $2)
  59. if [ $type1 = $type2 ]; then
  60. case $type1 in
  61. file)
  62. comparefile $1 $2
  63. ;;
  64. directory)
  65. comparedirectory $1 $2
  66. ;;
  67. softlink)
  68. comparesoftlink $1 $2
  69. ;;
  70. *)
  71. echo "$1 of unknown type"
  72. false
  73. ;;
  74. esac
  75. else
  76. echo "type mismatch: $type1 ($1) and $type2 ($2)."
  77. false
  78. fi
  79. return
  80. }
  81. if [ 2 -ne $# ]; then
  82. cat << EOU
  83. Usage: $0 dir1 dir2
  84. Compare directory trees:
  85. files are binary compared (cmp)
  86. directories are checked for identical content
  87. soft links are checked for identical targets
  88. EOU
  89. exit 10
  90. fi
  91. compare $1 $2
  92. exit $?