I'm new to bash scripting. I have pieced together a bash script to rsync my website files and databases.
Any guidance on ways I could improve or make my script more secure would be greatly appreciated.
#!/bin/bash
set -e
site_host=(
"[email protected]"
"[email protected]"
)
backup_dest=(
"/Users/computername/Desktop/rsync/site1.co.uk"
"/Users/computername/Desktop/rsync/site2.co.uk"
)
now=`date "+%d/%m/%Y %H:%M:%S"`
today=`date +"%d-%m-%Y"`
yesterday=`date -v -1d +"%d-%m-%Y"`
backup_old=`date -v -2d +"%d-%m-%Y"`
log="/Users/computername/Desktop/rsync/rsync.log"
site_count=${#site_host[@]}
db_creds=()
db_creds+=("")
db_creds+=("localhost,user,pass,dbname")
for (( i = 0; i < site_count; i++ )); do
# Source and destination
site_source="${site_host[$i]}:~/public_html"
site_dest="${backup_dest[$i]}/$today/"
# DB creds
for val in ${db_creds[$i]}; do
subset=($(echo $val | tr ',' ' '))
db_host=${subset[0]}
db_user=${subset[1]}
db_pass=${subset[2]}
db_name=${subset[3]}
done
if [ "$db_host" ]; then
# Set DB seperate directory
mkdir -p ${backup_dest[$i]}/$today/db
# Database backup
ssh -p22 ${site_host[$i]} "mysqldump \
--host=$db_host \
--user=$db_user \
--password=$db_pass \
--databases $db_name \
--lock-tables \
| bzip2" > ${backup_dest[$i]}/$today/db/$today.sql.bz2
echo "$now - SUCCESS - DB Backup - ${backup_dest[$i]}/$today/db/$today.sql.bz2" >> $log
fi
# Remove old backups
if [ -d "${backup_dest[$i]}/$backup_old" ]; then
rm -Rf ${backup_dest[$i]}/$backup_old;
echo "$now - DELETED - Full Backup - ${backup_dest[$i]}/$backup_old" >> $log
fi
if rsync -zavx -e 'ssh -p22' \
--numeric-ids \
--delete -r \
--link-dest=../$yesterday $site_source $site_dest;
then
echo "$now - SUCCESS - File Backup - ${backup_dest[$i]}/$today" >> $log
else
echo "$now - FAILED - File Backup - ${backup_dest[$i]}/$today" >> $log
fi
done