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.

#!/bin/bash

set -e
set -u

DATESTAMP=`date ‘+%d_%m_%Y-%H%M’` #Date will appear in day_month_year-hour&min format
EMAIL=”user@uni.edu.au” #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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: