sync_dir.sh 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/bin/bash
  2. # Function to display usage information
  3. usage() {
  4. echo "Usage: $0 [-n|--dry-run] <source_directory> <destination_directory>"
  5. echo "Options:"
  6. echo " -n, --dry-run Perform a trial run with no changes made"
  7. exit 1
  8. }
  9. # Default dry run flag
  10. DRY_RUN=false
  11. # Parse command-line arguments
  12. ARGS=$(getopt -o n -l dry-run -n "$0" -- "$@")
  13. if [ $? -ne 0 ]; then
  14. usage
  15. fi
  16. eval set -- "$ARGS"
  17. # Process arguments
  18. while true; do
  19. case "$1" in
  20. -n|--dry-run)
  21. DRY_RUN=true
  22. shift
  23. ;;
  24. --)
  25. shift
  26. break
  27. ;;
  28. *)
  29. usage
  30. ;;
  31. esac
  32. done
  33. # Check if source and destination paths are provided
  34. if [ $# -ne 2 ]; then
  35. usage
  36. fi
  37. # Assign input arguments to variables
  38. SOURCE_DIR="$1"
  39. DEST_DIR="$2"
  40. # Validate source directory exists
  41. if [ ! -d "$SOURCE_DIR" ]; then
  42. echo "Error: Source directory does not exist"
  43. exit 1
  44. fi
  45. # Create destination directory if it doesn't exist (unless dry run)
  46. if [ "$DRY_RUN" = false ]; then
  47. mkdir -p "$DEST_DIR"
  48. fi
  49. # Prepare rsync options
  50. RSYNC_OPTS="-av"
  51. # Add dry run option if specified
  52. if [ "$DRY_RUN" = true ]; then
  53. RSYNC_OPTS+=" --dry-run"
  54. echo "=== PERFORMING DRY RUN (NO CHANGES WILL BE MADE) ==="
  55. fi
  56. # Add compression and delete options
  57. RSYNC_OPTS+=" -z --delete"
  58. # Perform rsync
  59. rsync $RSYNC_OPTS "$SOURCE_DIR/" "$DEST_DIR"
  60. # Check rsync exit status
  61. if [ $? -eq 0 ]; then
  62. if [ "$DRY_RUN" = true ]; then
  63. echo "Dry run completed successfully. No changes were made."
  64. else
  65. echo "Synchronization completed successfully"
  66. fi
  67. else
  68. echo "Synchronization failed"
  69. exit 1
  70. fi