Passing exit status to an exit_handler

Hi!,

I have a exit_handler to do post-processing when the programs exits with some value.

Here is my code:

trap 'exit_handler ' EXIT

exit_handler()
{
status=$?
print -u2 "inside the exit handler with status as $status"
}

exit 2

But when i run this orgram, this is the output I get.

inside the exit handler with status as 0

The exit code in the handler is "0" and not "2".

Could you suggest me a way by which the correct exit code can be passed to the exit_handler.

Thanks,
Jyoti

Well - you can override the exit builtin (in bash) with a function

#!/bin/bash

exit() {
  echo "Inside exit handler: $1"
  # don't call exit again - otherwise you'll
  # get an infinite loop!
}

exit 2

Obviously this is a bit of a kludge.

I'd say it'd be easiest to write your own exit function and then call that function instead of exit when you leave the program, e.g.

#!/bin/bash

my_exit()
{
  echo "We want to exit with status $1"
  exit $1
}

my_exit 2

Yet another way to do it (and how I'd personally go about it) would be to call your script from within another script. You could then test the value of $? and process accordingly... e.g.

#!/bin/sh

/path/to/myscript
exitstatus=$?
echo "My script exited with exit status $exitstatus"
case $exitstatus in
  0)	echo "All is well" 
        ;;
  *)    echo "Oh dear"     
        ;;
esac

exit 0

Cheers
ZB