Advertisement
Guest User

Untitled

a guest
Aug 18th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. ## README
  4. #
  5. # Automatic PostgreSQL backup script
  6. # Version: v1.0.0
  7. # Author: Emzi0767
  8. # Usage:
  9. # ./backup_db.sh <database> <username> <password> <max_count>
  10. #
  11. # Use with cron. This script will automatically backup your
  12. # PostgreSQL database, compress the backup
  13.  
  14. NAME="Automatic PostgreSQL backup script"
  15. VERSION="v1.0.0"
  16. AUTHOR="Emzi0767"
  17. USAGE="./backup_db.sh <database> <username> <password> <max_count>"
  18.  
  19. do_backup() {
  20. echo "Beginning database backup..."
  21.  
  22. #############################
  23. # Backup initialisation logic
  24. #############################
  25.  
  26. targetdir="/home/emzi0767/dat/db_backups/$1"
  27.  
  28. # Check if the directory doesn't exist, and if it doesn't, create it
  29. if [ ! -d "$targetdir" ]
  30. then
  31. echo "Target directory ($targetdir) doesn't exist, creating"
  32. mkdir "$targetdir"
  33. fi
  34.  
  35. # Enter the target directory
  36. cd "$targetdir"
  37.  
  38. #############################
  39. # Postgres backup logic
  40. #############################
  41.  
  42. filename="$1_$(date +%s).sql"
  43.  
  44. echo "Database: $1"
  45. echo "Username: $2"
  46. echo "Target: $filename"
  47.  
  48. # Dump the database
  49. PGPASSWORD="$3" pg_dump -U "$2" -d "$1" > "$filename"
  50.  
  51. echo "Postgres dump completed, compressing"
  52.  
  53. xz -z9e "$filename"
  54.  
  55. echo "Completed"
  56.  
  57. #############################
  58. # Backup trimming logic
  59. #############################
  60.  
  61. files=$(ls -1 | grep '\.sql$' | tail -n +$4)
  62. filecount=$(echo -n "$files" | wc -l)
  63.  
  64. echo "Trimming backups to $4 latest"
  65. echo "Will remove $filecount files"
  66.  
  67. for i in $files
  68. do
  69. echo "Removed $i"
  70. rm $i
  71. done
  72.  
  73. echo "Backups trimmed"
  74. }
  75.  
  76. print_usage() {
  77. echo "$NAME $VERSION by $AUTHOR"
  78. echo "Usage:"
  79. echo " $USAGE"
  80. }
  81.  
  82. if [ "$1" == "--help" ] || [ "$1" == "-h" ]
  83. then
  84. print_usage
  85. elif [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ] || [ -z "$4" ]
  86. then
  87. print_usage
  88. else
  89. do_backup "$1" "$2" "$3" "$4"
  90. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement