I haven't used Unix, etc. for 40 years, so I am a bit rusty. I need to back up the databases on my website(s) once a week and then retrieve them automatically from my development machine. So this is step one and is working fine as a crontab job on Apache. It emails me a message with status/error.
- I am creating a folder with the date as name and keeping 14 backups.
- I am not using a loop for the databases, because each one has a different user/pwd combination.
- I don't see it dangerous to have the username and passwords here. If someone has root access, they can access the database anyway.
- The file size is returned as well.
- The start time and finish time are returned, so I can calculate how long the job took.
How can make it more generic, or faster, or safer? Am I catching all the errors?
#!/usr/bin/bash
TIMESTAMP=$(date +"%F")
BACKUP_DIR=backup
MYSQLDUMP=/usr/bin/mysqldump
STAT=/usr/bin/stat
EMAIL=***
KEEP="+14"
MSG=tmp/backup_msg
echo "Date: $(date)" > $MSG
echo "Hostname: $(hostname)" >> $MSG
echo " " >> $MSG
echo " " >> $MSG
mkdir -p "$BACKUP_DIR/$TIMESTAMP" 2>> $MSG
DB=xxx_directory
BKP=$BACKUP_DIR/$TIMESTAMP/db_biz_directory.sql
echo "Backing up '$DB' to '$BKP'" >> $MSG
$MYSQLDUMP -u username -ppassword $DB > $BKP 2>> $MSG
SIZE=$($STAT -c%s $BKP) 2>> $MSG
echo "Filesize: $SIZE" >> $MSG
echo " " >> $MSG
DB=xxx_software
BKP=$BACKUP_DIR/$TIMESTAMP/db_swr_software.sql
echo "Backing up '$DB' to '$BKP'" >> $MSG
$MYSQLDUMP -u username -ppassword $DB > $BKP 2>> $MSG
SIZE=$($STAT -c%s $BKP) 2>> $MSG
echo "Filesize: $SIZE" >> $MSG
echo " " >> $MSG
echo "Removing excess backups" >> $MSG
find $BACKUP_DIR* -mtime $KEEP -exec rm {} \; >> $MSG 2>> $MSG
echo "Finished: $(date)" >> $MSG
mail -s "MySQL Backup script has run" "$EMAIL" <$MSG
rm -f $MSG
GETSIZE="/usr/bin/stat -c%s"
, thenSIZE=$($GETSIZE $BKP 2>>$MSG)
. (The2>>
won't work the way you want if you put it outside the$()
). \$\endgroup\$