I am backing small databases from several websites and sending the admin an email with the results. I have already directed stderr to send the complete error in the email. Is there a way I can detect whether an error occurred so that I can change the email subject to match?
I am using two files, the first just sets things up and is different in each site.
#!/usr/bin/bash
#set -euo pipefail
set -u
email="admin@example.com"
keep="+14"
#include script
. cronjobs/do_backup.sh
echo Main
#mysql Config File
dbcfg="cronjobs/_dbaccess.cnf"
#Backup using database, group_suffix in cnf file and backup_name
db="zzzcity_directory"
dbgrp="_zzz_directory"
bkp="db_zzz_directory.sql"
backup $db $dbcfg $dbgrp $bkp &>>$msg
#Backup using database, group_suffix in cnf file and backup_name
db="zzzcity_potluck"
dbgrp="_zzz_potluck"
bkp="db_zzz_potluck.sql"
backup $db $dbcfg $dbgrp $bkp &>>$msg
#Maintain backup copies and send email
finalize $keep $email
echo Done
The second one is identical on every site.
do_backup.sh
#!/usr/bin/bash
timestamp=$(date +"%F")
backup_dir="backup"
mysqldump="/usr/bin/mysqldump"
stat="/usr/bin/stat"
msg="tmp/backup_msg"
echo "Date: $(date)" > $msg
echo "Hostname: $(hostname)" >> $msg
echo >> $msg
echo >> $msg
mkdir -p "$backup_dir/$timestamp" 2>> $msg
main() {
db=$1
dbcfg=$2
dbpgrp=$3
bkp="$backup_dir/$timestamp/$4"
echo "Backing: $db"
echo "To: $bkp"
$mysqldump --defaults-extra-file=$dbcfg --defaults-group-suffix=$dbgrp $db > $bkp
size=$($stat -c%s $bkp)
echo "Filesize: $size"
echo
}
backup () {
main $1 $2 $3 $4
}
finish () {
keep=$1
echo "Keeping: $keep copies"
echo "Removing excess backups"
find $backup_dir/ -type d -mtime +$keep -exec rm -r {} +
echo
echo "Finished: $(date)"
}
finalize (){
finish $1 &>>$msg
mail -s "MySQL Backup script has run" "$2" <$msg
#rm -f $MSG
}
Further explanation
- It's run using cron, once a day at 2 am
- It's backing up MySQL databases with authentication in a
.cnf
file - I am keeping 14 copies in directories whose names are the date of backup
- The oldest gets deleted
The email looks like this
Date: Tue May 9 02:00:02 AEST 2023
Hostname: zzzBacking: zzzcity_directory
To: backup/2023-05-09/db_zzz_directory.sql
Filesize: 6463Backing: zzzcity_potluck
To: backup/2023-05-09/db_zzz_potluck.sql
Filesize: 3541Keeping: +14 copies
Removing excess backupsFinished: Tue May 9 02:00:04 AEST 2023
Question
At the moment, the subject of the email is static. I would like to change it if there is an error. Otherwise, I have to open all the emails. Since I have already used stderr to build up the details in the email, how do I obtain an indication that something has failed? Two that come to mind are mysqldump or filesystem errors.
mysqldump
ran correctly? Take a look at the return code, should be0
if everything worked. – Panki May 09 '23 at 07:48