Exiting from script when error occurs

Hi Friends,

Is it possible to exit nicely(ie, to echo a message with the error occurred) from a shell script(quiet a big one :)) once it encounter an error in between the lines?

For example, in my script I am calling the command mkdir and sometimes (when the directory already exists) it fails.then i want my script to exit with the error message.Currently it passes to the next command.

I tried using the below function at the start of the script:

#!/bin/sh
check_errs()
{
  if [ "${1}" -ne "0" ]; then
    echo "ERROR # ${1} : ${2}"
    exit ${1}
  fi
}

#main script
mkdir newdir_$sid
check_errs $?

but calling this function after every command sounds :confused:

Can any one give me pointers on how to call this function after every command executed or someother method by which i can exit from program as soon as an error occurs...

Make directory Or exit

mkdir newdir_$sid || echo "Can not create newdir_$sid, exit now"; exit;

Thanks a lot danmero..
This is working fine...

Is there any way of using trap commad and do the same?So that I dont have to use everywhere

If you just want tio exit from the script when an error occurs, add the following command :

set -e

You can also specify a trap routine :

trap 'echo "Error detected! End of script.";exit 1' ERR
#set -e
argr="$1"
if [ -n "$arg" ]
then
   cat $arg.err
else
   echo "Empty arg"
fi
echo "done!"

Jean-Pierre.

WOW!!
Thanks Jean..really greatfull to you for passing this info..
This is working fine....