1

I am writing a shell script to automate the sql metadata backup everyday. I am stuck in between. My approach is to backup sql metadata everyday and delete the old backups keeping last 3 backup for safety. Please help me out with the command to delete the previous backups keeping the last 3 backups.

FILE= mysql_metadata_backup_$( date '+%Y-%m-%d_%H-%M-%S' ).sql
mysqldump -u userID --all-databases > ${FILE}
Shadow
  • 33,525
  • 10
  • 51
  • 64
Naveen
  • 123
  • 3
  • 15

1 Answers1

0

I guess you could use bash parameter expansion to achieve your objective.

Place the below bash script in the folder containing your backups.

#!/bin/bash
file_list=($( ls -t mysql_metadata_backup*))
# The '-t' parameter of the 'ls' sorts the output according to modification time with newest displayed first.
rm $( echo ${file_list[@]:3})
# The ':3' does the magic slicing the array from the index 3
# All the files except the newest three are passed to the "rm" command.

Running it will delete all the backups except the newest three.

Perhaps you could consider adding a cron job to automate this.

Reference:

Bash Parameter Expansion

sjsam
  • 21,411
  • 5
  • 55
  • 102
  • I placed the file in the same folder and ran the script. its giving error. ls: cannot access mysql_metadata_backup_Sat: No such file or directory – Naveen Dec 19 '15 at 23:37
  • `FILE= mysql_metadata_backup_$( date '+%Y-%m-%d_%H-%M-%S' ).sql` is incorrect i guess. You could do `temp=$( date '+%Y-%m-%d_%H-%M-%S') && FILE=mysql_backup_$temp.sql` – sjsam Dec 20 '15 at 02:37
  • Awesome Sjsam, It worked with your last answer. Thanks a lot – Naveen Dec 20 '15 at 03:31
  • Sjsam the code works fine but I dont want to enter my password in the script file. Can you suggest me on that. – Naveen Dec 20 '15 at 04:02
  • @Naveen : Regarding the password, see [this](http://stackoverflow.com/questions/9293042/mysqldump-without-the-password-prompt) – sjsam Dec 21 '15 at 01:49