Advertisement
Guest User

Untitled

a guest
Oct 21st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.88 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. include=""
  4. exclude=""
  5. user=""
  6. host=""
  7. key=""
  8. force=false
  9. target=""
  10.  
  11. while getopts u:h:k:s:o:f:e:i: option
  12. do
  13.     case "${option}" in
  14.         u) user=${OPTARG};;
  15.         i) include=${OPTARG};;
  16.         e) exclude=${OPTARG};;
  17.         h) host=${OPTARG};;
  18.         k) key=${OPTARG};;
  19.         o) target=${OPTARG};;
  20.         f) force=true;;
  21.         *) ;;
  22.     esac
  23. done
  24.  
  25. if [ -z "$user" ] || [ -z "$host" ] || [ -z "$target" ]
  26. then
  27.     echo "Usage : $0 <-u : user> <-h : host> <-o : output directory> [-f : force full] [-k : key] [-i : include ONLY file] [-e : exclude file]"
  28.     exit 1
  29. fi
  30.  
  31. if [ ! -d "$target/../Backup" ]
  32. then
  33.     if [ ! -d "$target/Backup" ]
  34.     then
  35.         echo "Creating backup directory on target..."
  36.        
  37.         if ! mkdir "$target/Backup"
  38.         then
  39.             echo "Could not create the backup directory. Exiting."
  40.             exit 2
  41.         fi
  42.     fi
  43.     target="$target/Backup"
  44. fi
  45.  
  46. #Removing double slashes
  47. target=$(echo "$target" | sed -e "s#//#/#g")
  48.  
  49. rsync_args=(-ravh -H "--rsync-path=\"sudo rsync\"" --progress --safe-links)
  50. if [ -f "$key" ]
  51. then
  52.     rsync_args+=(-e \"ssh -i "$key"\")
  53. fi
  54. if [ -f "$include" ]
  55. then
  56.     echo "Including only files from $include"
  57.     rsync_args+=("--files-from=\"$include\"")
  58. fi
  59. if [ -f "$exclude" ]
  60. then
  61.     echo "Excluding files from $exclude"
  62.     rsync_args+=("--exclude-from=\"$exclude\"")
  63. fi
  64. if ! $force
  65. then
  66.     last_backup=$(basename "$(ls -td  "$target"/*/ 2>/dev/null | sed "y/\t/\n/" | head -n 1 )" 2>/dev/null)
  67.     if [ -n "$last_backup" ]
  68.     then
  69.         echo "Processing backup based on --> $last_backup"
  70.         rsync_args+=("--link-dest=\"../$last_backup\"")
  71.     else
  72.         echo "Processing full backup"
  73.     fi
  74. else
  75.     echo "Processing full backup"
  76. fi
  77.  
  78. target=$(echo "$target/$(date '+%Y_%m_%d')" | sed "s#//#/#g")
  79.  
  80. rsync "${rsync_args[@]}" "$user@$host:/" "$target" 2> error.log
  81.  
  82. CODE=$?
  83. if [ $CODE -eq 0 ]
  84. then
  85.     echo "Backup done : $target"
  86.     exit 0
  87. else
  88.     echo "Rsync stopped with code $CODE"
  89.     exit $CODE
  90. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement