Help needed with error handling

I am writing a wrapper to one of the .ksh script. The wrapper script should capture the error/fatal(if any) and exit out of the script. Here is the script:

#!/bin/sh

. main_script.ksh <arg1> <arg2> > mainscript.log 2>&1 

cnt=`grep 'ERROR' -c mainscript.log`

if [ $cnt -ne 0 ]; then
  echo "Error"
  grep 'ERROR' mainscript.log > error.txt  #Write the error to a file
  exit 1
else
  echo "Success"
fi

The above script is not doing what it is supposed to do. It is not erroring out and also not writing anything to the error.txt
When i take the execution of the main_Script.ksh from the script, it works fine but not when i am executing the main_script.ksh.

Please let me know where am i going wrong.

Thanks in advance!!

Try replacing:

cnt=`grep 'ERROR' -c mainscript.log`

by

cnt=`grep -c 'ERROR' mainscript.log`

I did try doing it that way as well but it didnt work..Anyway i really appreciate for taking time to reply..I somehow fixed the issue and here it is:

#!/bin/sh
err_code=0;
main_script.ksh <arg1> <arg2> > mainscript.log 2>&1 
cnt=`grep 'ERROR' -c mainscript.log`
if [ $cnt -ne 0 ]; then
  echo "Error"
  grep 'ERROR' mainscript.log > error.txt;  #Write the error to a file
  err_code=1;
else
  echo "Success"
fi
if [ $err_code -ne 0 ]; then
  echo "Error"
  exit $err_code;
else
  echo "Success"
  exit $err_code;
fi

Thanks Again!!

Nice you worked it out yourself, but it's still a little inefficient, your reading the whole file with grep to count the number of error lines and then re-reading it again to capture them.

Why not grep the error lines and redirect to error.txt and then test the size of error.txt with the -s option:

grep ERROR mainscript.log > error.txt
if [ -s error.txt ]; then
   echo Error
   ...
else
   rm error.txt
   echo Success
fi

May be yes...I can do it that way. This looks like a better approach instead of grep'g multiple times...Thanks a lot !!

In an ongoing battle against inefficiency (die! ;)), why not simply use grep's meaninful exit status directly?

 if grep ERROR mainscript.log > error.txt; then...

Regards,
Alister

Thanks for all the suggestions...!!