1

I have a backup script to run as a cron job and create a daily backup of /var/log/messages/. Please note this script is more for learning experience than actual application. I have added if / else statements to check the exit code after the tar command is executed. The script worked fine before, but after I added this feature it hangs. Code below:

#!/bin/bash

admin="[email protected]"
of=messages-backup-$(date +%Y%m%d).tgz

cd /var/log/

tar -czvf $of messages

if [ $? -eq 0 ]; then
  mail -s "Backup of /var/log/messages was successful!" $admin
  exit 0
else
  mail -s "Backup of /var/log/messages has failed!" $admin
  exit 1
fi

cp $of /home/user/
rm -rf $of

Output:

[root@nidesant2 Scripts]# ./backup.sh 
messages
^C
(Interrupt -- one more to kill letter)
2
  • 1
    mail is expecting an input, just add echo hello | in front of mail
    – Archemar
    Commented Sep 27, 2016 at 18:54
  • Or 'mail -s "subject" $admin </dev/null
    – mdpc
    Commented Sep 27, 2016 at 19:26

1 Answer 1

4

Change

mail -s "Backup of /var/log/messages was successful!" $admin

to

echo hello | mail -s "Backup of /var/log/messages was successful!" $admin

or

mail -s "Backup of /var/log/messages was successful!" $admin < /dev/null

The first option, you can use whatever text you like for the message body. The second option will send the email with an empty message body. Repeat the same change for the second email command for an unsuccessful backup.

For learning purposes, you should check the successful completion of creating the tar file, copying it, and deleting it before determining that it was successful. To do that, you could do this.

Change

tar -czvf $of messages

to

tar -czvf $of messages && cp $of /home/user/ && rm -rf $of

Also, with this change you would remove cp $of /home/user/ and rm -rf $of from the end of the script.

Then your if/else will execute based on the successful completion of all three commands or an unsuccessful completion of any one of the three commands in that string.

1
  • If the answer works for you, please click the check mark below the answer to accept it.
    – MikeA
    Commented Sep 27, 2016 at 19:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .