I want my ksh script to stop on unexpected error. I also use functions that I nest to reuse recurrent code.
So I use errexit feature ('set -e'). The script crashes on error -> great.
I sometime want to catch the error instead of crashing.
I have a function func. I want that (requirements):
in the function: it should stop on error
in the parent: it should also stop on error
except that in the parent, error when executing 'function' should be caught
I coded this:
# parent script
func()
{ (
set -e # function should crash on 1st error
rm foo ; rm foo # this will trigger error
echo "Since -e is set, this part of the script should never get reached"
) }
set -e # parent script should crash on 1st error
echo "do stuff"
# we want to execute 'function' and catch error
if func ; then
echo "Execution of func was ok"
else
echo "Execution of func was not ok"
fi
echo "do more stuff"
It does not work.
do stuff
rm: impossible de supprimer 'foo': No such file or directory
rm: impossible de supprimer 'foo': No such file or directory
Since -e is set, this part of the script should never get reached
Execution of func was ok
do more stuff
Since 'func' is executed within a test (if func), the errexit is disabled. This means that errors inside func do not crash the function. The function proceeds and exits with status 0, and the parent is not notified of the error. Even if I explicitly set again errexit inside func, the errexit is not enabled.
If I do not execute func in a test, the errexit kicks in and the parent crashes: I cannot catch the exception (in other words: I'm func'ed). I could temporary disable errexit around the call of func, but it seems like an unclean workaround.
Any idea how I could reach my requirements?