How to automatically send a mail alert if the script errors out

I have a script like this, which calls other scripts from that script:

#!/usr/ksh

moveFiles.sh

extract.sh

readfile=/home/sample.txt

cat $readfile | while read line

do 

file= `echo $line|awk '{print $4}'`

if [ $file ];
       then mv $file /home/temp_stage
fi

done

I have to write the above script in such a manner that if it errors out any point, It has to automatically send an email notification. How do i find out if the file has errored out at any point.
I am struck at the point of... how to find if there is any error in the scripts that it calls...

Ur help is greatly appreciated.
Thanks in advance!

try something like this:

#!/usr/ksh
email_it()
{
   echo "This script had an error on line $1" | /usr/bin/mailx -s 'script error' me@mycomputer.com
   exit 1
}

moveFiles.sh  || email_t $LINENO
extract.sh || email_t $LINENO

readfile=/home/sample.txt
cat $readfile | while read line
do 
  file= `echo $line|awk '{print $4}'`

  if [ $file ];
  then 
        mv $file /home/temp_stage
  fi
done

This assumes the other scripts return non-zero (i.e., exit 1) on error.

1 Like

Thanks Jim.

Let me try with that.
Can u please explain to me, what does this "||" stand for in unix and hoe does it work?
I have never used it before.

The "||" means only run what is after the "||" if the code before the "||" fails, the opposite is "&&" which means only run what is after the "&&" if the code before the "&&" has succeeded, e.g.:

cp fred /var && rm fred

Only delete fred if it was successfully copied to /var.

1 Like

Thanks Tony!