I'm quite a novice in shell scripting so far, but i'm learning and getting quite comfortable in writing shell scripts, but i have a lot to learn.
The snippet at the bottom of the page creates backups of a certain users databases.
The script checks first if there is more than 7 compressed .gz files in a folder.
Fetches oldest gz archive and removes it.
Checks for latest .sql backup and compresses it with gzip
Creates a new .sql dump
The script is run once a day
How would you write this differently?
#!/bin/bash
BACKUPPATH=/var/mysql_backup/
mkdir -p $BACKUPPATH
if [ $(ls -l $BACKUPPATH*.gz 2>/dev/null | wc -l) -gt 7 ]; then
OLD=$(find $BACKUPPATH -type f -name '*.gz' -printf '%T+ %p\n' | sort | head -n 1 | awk '{print $2}')
rm $OLD # Removing oldest compressed archive
fi
if [ $(ls -l $BACKUPPATH*.sql 2>/dev/null | wc -l) -eq 1 ]; then
LATESTLOG=$(find $BACKUPPATH -type f -name '*.sql' -printf '%p\n' | head -n 1)
gzip $LATESTLOG
fi
/usr/bin/mysqldump -u db_user -p'password' --single-transaction --all-databases > $BACKUPPATH$(date "+%Y.%m.%d-%H.%M.%S")_dump.sql