Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.67 KB | None | 0 0
  1. #!/bin/sh
  2.  
  3. # The database name is had from the filename, so ensure the file is named
  4. # backup_DATABASENAME.sh or this will crash. Set the other relevant vars here.
  5.  
  6. # Definitely need to change these:
  7. USER='USER_NAME'
  8. PASSWORD='PASSWORD'
  9.  
  10. # Might need to change these:
  11. HOST=localhost
  12. FOLDER='backups/'
  13. #!/bin/sh
  14.  
  15. ########################### Do not edit below this line #######################
  16.  
  17. TARGET=`expr match "$0" '\(.*\)bash/backup_.*'`
  18. TARGET=$TARGET$FOLDER
  19. DB=`expr match "$0" '.*backup_\(.*\).sh'`
  20. # Simpler to just use seconds everywhere
  21. NOW=`date +"%s"`
  22.  
  23. mysqldump -h $HOST -u $USER -p$PASSWORD $DB > $TARGET$DB'_'$NOW.sql
  24.  
  25. bzip2 -f $TARGET$DB'_'$NOW.sql
  26.  
  27. echo Backed up database $DB on $HOST to $TARGET$DB'_'$NOW.sql.bz2
  28.  
  29.  
  30.  
  31. days_diff()
  32. # Echos difference in days between exisiting files and arg1 an epoch timestamp.
  33. {
  34.     ref_time=$1
  35.     FILE_2=`expr match "$2" '.*_\(.*\)\.sql.*'`
  36.     INTER=$(($ref_time-$FILE_2))
  37.     echo $(($INTER/86400))
  38. }
  39.  
  40. divisible_by_six() # The frequency with which we'll delete files.
  41. {
  42.     REMAINDER=$(( $1 % 6 ))
  43.     if [ $REMAINDER -eq 0 ]
  44.     then
  45.         echo "1"
  46.     else
  47.         echo "0"
  48.     fi
  49. }
  50.  
  51. process_files() # Removes every sixth file that's more than a week old.
  52. {
  53.     COUNTER=0    
  54.     find $1 -maxdepth 1 -type f | while read -r dir
  55.     do
  56.         VAL=$(basename ${dir})
  57.         DIFF=`days_diff $2 $VAL`
  58.         if [ "$DIFF" -gt 6 ]
  59.         then
  60.             let COUNTER=$COUNTER+1 # Only care about older files
  61.             DIV=`divisible_by_six "$COUNTER"`
  62.             if [ $DIV -eq 1 ]
  63.                 then
  64.                 echo "Deleting $1$VAL"
  65.                 rm "$1$VAL"
  66.             fi
  67.         fi
  68.     done
  69. }
  70.  
  71. echo `process_files $TARGET $NOW`
  72.  
  73. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement