Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have some scripts that do usual stuff like backing up MySql database, gz, tar some files and put them on FTP or sync with some other backup/mirror system. Some scripts are running quite frequently (like twice/thrice per hour). I am sending email with attached log output from commands after completion of job. It is quite a lot of email to keep track of.

I want to send email only when script fails to do something, that is when some command in script fails. How can I accomplish this?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

Check the return value of the command and proceed accordingly. Normally all the Linux commands return 0 on success and some other number(specifying the reason) on failure.

Update:
Forgot to mention that the status of last command is saved in variable "$?". Thanks @bbaja42

share|improve this answer
    
suppose I run a command using curl like curl --upload-file..... in a script how will I check status? i = curl --upload-file... then if [i eq 0]? –  TheVillageIdiot Jun 29 '11 at 19:43
2  
Status of last command is saved in variable "$?", so you can use [ $? -eq 0 ] –  bbaja42 Jun 29 '11 at 19:49
2  
@TheVillageIdiot: Example. –  grawity Jun 29 '11 at 20:04
    
@bbaja42 and @grawity thanks for clearing up the things. I'm accepting @ssapkota's answer. –  TheVillageIdiot Jun 30 '11 at 5:42

here is an example of script that I wrote for my work that's being used on daily basis

[alexus@wcmisdlin02 ~]$ sudo cat /usr/local/uftwf/mysql/_mysql.sh
#!/bin/sh
# $Id: _mysql.sh,v 1.2 2011/05/31 16:02:56 alexus Exp $

if [ -d /var/lib/mysql/ ]; then
    cd /var/lib/mysql/
    for i in `ls`; do
            /usr/bin/mysqldump \
                --user=root \
                $i > /usr/local/uftwf/mysql/$i.sql
            /bin/gzip \
                --force \
                --quiet \
                /usr/local/uftwf/mysql/$i.sql
    done
    /usr/bin/mysqladmin \
        --user=root \
        flush-logs
    /usr/bin/mysql \
        --user=root \
        --execute='PURGE BINARY LOGS BEFORE subdate(curdate(), INTERVAL 1 DAY);'
fi
[alexus@wcmisdlin02 ~]$ 


[alexus@wcmisdlin02 ~]$ sudo crontab -l -u mysql
@daily      /usr/local/uftwf/mysql/_mysql.sh
[alexus@wcmisdlin02 ~]$ 

it will only email you once you get some sort of an error, it will not mail if job ran ok. This shell script resides in /usr/local/uftwf/mysql and that's where backups goes as well. Modify this script to FTP/rsync files to your remote location.

share|improve this answer
1  
Where's the conditional emailing bit? –  Linker3000 Jun 29 '11 at 21:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.