Thursday, November 5, 2015

exception handling in shell script

Problem :

I have a a situation where I want to execute script1 and then script 2 in sequence.. But at same time want to make sure if script1 fails, script2 doesn't get executed. In this case I want to explain how to break the script if there were some errors in

lets create twp scripts script1.sh as below

#!bin/ksh
echo " this is with in script 1 "

create script2.sh as below

#!bin/ksh
echo " this is with in script 2 "


now lets create another script handle_errors.sh as below

#!bin/ksh
script1.sh
rc=$?
if [ ${rc} -eq 0 ];then
echo "script1 pass, starting script2"
  script2.sh
  rc=$?
  if [ ${rc} -eq 0 ];then
   echo "script2 pass"
  else
   echo "script2 failed"
  fi
else
 echo "script1 failed"
fi

Sample output :

atoorpu@Linux01:[~/scripts] $ . handle_errors.sh
this is from script1
script1 passed, starting script2 now !!
 this is from script2
script2 has passed
atoorpu@Linux01:[~/scripts] $


now if  you want to mess around you can update one of script1 or script2 :

I changed script1.sh to below now :

#/bin/sh
this is from script1"


If you see here the script has failed on script1 and it didn't go to script2 

atoorpu@Linux01:[~/scripts] $ . handle_errors.sh
-bash: /home/atoorpu/scripts/script1.sh: line 2: unexpected EOF while looking for matching `"'
-bash: /home/atoorpu/scripts/script1.sh: line 4: syntax error: unexpected end of file
script1 failed !!


No comments:

Post a Comment