Posts Tagged ‘stdout’

Bash Script: Time, Tar, Date & Email

As im trying to learn bash scripting its easier if you have a little idea of a script that can be useful to you. For this example I want to backup a set of files/directories and have the script email me with the date, contents of the tar and the time it took to run the process…not as easy as it looks due to the “time command” outputting to stderr. The script can then be used as a cron job.


set -e
set -u

DATESTAMP=`date ‘+%d_%m_%Y-%H%M’` #Date will appear in day_month_year-hour&min format
EMAIL=”” #Define an email address for mail to use
SUBJECT=”Backup completed for PC-HTPC $DATESTAMP” #Create a subject for the mail including the date defined above
ARCHIVE=”backup_$DATESTAMP.tar.gz” #Create a name for the tarfile including the date defined above
BODY=`(time tar -cvpzf $ARCHIVE test*) 2>&1`#The tar command (including being timed) and redirecting stderr to stdout

echo -e “$ARCHIVE\n\n$BODY” | mail -s “$SUBJECT” “$EMAIL” #Using the variables archive and body and using the mail command to send the email