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:


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
  mail -s "Backup of /var/log/messages has failed!" $admin
  exit 1

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


[root@nidesant2 Scripts]# ./backup.sh 
(Interrupt -- one more to kill letter)
  • 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



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


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


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.


tar -czvf $of messages


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.

  • 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 .