I wrote a bash script to automatically backup a server and upload it to a server level FTP server. I'm somewhat new to the making of crontasks and other stuff heavily related to Linux administration. It took me a few days but I got it to work. I am now wondering if there are any ways to clean it up or simplify it.
#! /bin/bash
##Actual Backup Script Info
SRVDIR="/home/Minecraft/SERVER/"
SAVETO="/home/backup"
SCRNAME="Screen Name"
## FTP LOGIN
USER="-----"
PASS="----"
HOST="ip or domain"
##
cd $SAVETO
mkdir $(date +\%Y-\%m-\%d)
cd $(date +\%Y-\%m-\%d)
screen -r $SCRNAME -X stuff "say Starting Server Backup $(echo -ne '\r')"
screen -r $SCRNAME -X stuff "say Please Excuse any Lag While Backing up $(echo -ne '\r')"
screen -r $SCRNAME -X stuff "save-off $(echo -ne '\r')"
tar czf $SAVETO/$(date +\%Y-\%m-\%d)/$SCRNAME$(date +\%Y-\%m-\%d).tar.gz $SRVDIR
screen -r $SCRNAME -X stuff "save-on $(echo -ne '\r')"
screen -r $SCRNAME -X stuff "say Backup Complete $(echo -ne '\r')"
cd $SAVETO/$(date +\%Y-\%m-\%d)
ftp -n -v $HOST << EOT
quote USER $USER
quote PASS $PASS
mkdir $(date +\%Y-\%m-\%d)
cd $(date +\%Y-\%m-\%d)
put $SCRNAME$(date +\%Y-\%m-\%d).tar.gz
bye
EOT
exit
1 Answer 1
It is a bad practice to have passwords in a script. Maybe it would be wiser to use scp rather than ftp, it all depends on your network infrastructure and where you place the security boundaries.
It would be a good practice to put the final message just before the exit statement.
But there is worse :
Since you mention crontasks, then your script is very dangerous if ran in that context. Nobody read cron log files, you need to setup some notification way (mail -s "backup failed") to proactively raise an alarm.
your tar and ftp are unlikely to survive to any mishap, and your backup script will still process to completion, even if the case of complete failure (disks full, network failure, remote host missing ...). you should test the result of the tar command and the ftp command and take the appropriate actions (an explicit message) .
It is not very complex to figure out if the destination support is ok (df -k $saveto), and if the tar file is truncated (you do want backup you wish to restore, do you ? tar -tfz) and take the appropriate action (possibly another error message).
It is not uncommon to have more code for error handling, than the code to perform an action. In your case, the ratio (error detection / work done) is 0. As a quick guideline, make it larger than 2.
$(date ...)
. Stash it once in a parameter and reuse that parameter. Even though it's only at day resolution you still have a race condition. \$\endgroup\$