Bash Shell Scripting Crash Course crowfly.net
<< >> Introduction GNU_Tools Example1 Example2 Execution_bit Bang_bin_bash Example3 The_dot Example4 Example5 Example6 Example7 Example8 Background Forking Example9 Bash_profile Pattern_match Regex Debug Gory_details References << >> |
Example 9
Here we have our nightly database backup script that runs in a cron job:
Notice the use of:
- if/else structures;
- for loop structures;
- branching on file existance check; and
- the use of strong (') and week (") quotes.
backup_databases:
#!/bin/bash
# Backup,
# Move to off-line to Backup Server, and
# Vacuum
# 03-Jun-2003 -dvl
# 08-Dec-2004 -dvl brought to viddev1
# 24-May-2005 -im group write permission to db dump file
# 11-Oct-2005 -dvl reworked to use archive.pl
# Tweak these as need be ----------------
dblist="prod1 prod2"
do_schema=1
do_nonsales=1
do_sales=1;
years="2006" # 2003 2002 2001 2000"
vacuum=1
# ----------------------------------------
logdir=/var/log
bkupdir=/backup
storage_dir="/backups/$HOSTNAME"
weekday=`date|cut -c1-3`
# function: copy_to_storage
# must split files greater than 2gig due to microsoft limitation
gig=1073741824
gig1_5=1610612736 # 1.5 Gig
let two_gig=$gig*2
function copy_to_storage () {
db=$1;
file_extension=$2
logfile=$3
dump_file=${bkupdir}/${db}_${file_extension}
storage_file=${storage_dir}/${db}_${weekday}_$file_extension
size=$(ls -l $dump_file |cut -d' ' -f6)
if (( $size < $two_gig )) ; then
cp -v $dump_file $storage_file 2>&1 |tee -a $logfile
else
split --verbose -b$gig1_5 $dump_file $storage_file 2>&1 |tee -a $logfile
fi
}
if [ ! -d ${storage_dir} ] ; then
mount_netbackup
fi
if (( $vacuum )) ; then
opts='';
else
opts='-b'; # backup only (no vacuum)
fi
for db in $dblist; do
logfile=$logdir/${db}_backup.log
if (( $do_schema )) ; then
su -l postgres -s /bin/bash -c "archive.pl -nd $db -t schema"
copy_to_storage $db schema_dump.gz $logfile
fi
if (( $do_nonsales )) ; then
su -l postgres -s /bin/bash -c "archive.pl $opts -nd $db -t nonsales"
copy_to_storage $db nonsales_data.gz $logfile
fi
if (( $do_sales )) ; then
for year in $years; do
su -l postgres -s /bin/bash -c "archive.pl $opts -nd$db -tsales -y$year"
copy_to_storage $db sales_${year}_data.gz $logfile
done
fi
done;
|