On 2017-04-27, Janis Papanagnou <
janis_pa...@hotmail.com> wrote:
> I want to distinguish errors from quits using traps like this
>
> trap 'printf "An error occurred!\n" ; exit 8' ERR
> trap 'printf "Execution aborted!\n" ; exit 9' HUP INT QUIT TERM
> sleep 3 ; diff x
>
> but even with a ^C I only get the first trap triggerd with
>
> $ ksh --version
> version sh (AT&T Research) 93u+ 2012-08-01
Is there any difference if you replace the sleep with a purely internal
action like "while true ; : done"?
Is there any difference if you reorder the trap commands?
Wildly unlikely: maybe they are registered in some ordered list, and if
both situations apply (command failed because of Ctrl-C), only the first
eligible trap is processed. (Grasping-at-straws wild assed guess).
> Above code behaves as expected with bash and zsh. Is that a ksh bug?
> What would be a sensible workaround, preferably one that works also
> in bash and zsh, or functional code conforming to POSIX standard?
In the past I have written scripts which trapped failing commands,
had a handler for an interrupt, and had exit cleanup actions also.
I did that using "set -e" to catch the failing commands rather than
the ERR trap, and an EXIT trap for the common cleanup action.
Perhaps these pieces can cob together an acceptable workaround here?
This program still behaves how we want on bash: how is it on your ksh?
sig_was_caught=
sig_handler()
{
sig_was_caught=y
exit 9
}
exit_handler()
{
saved_status=$?
if [ $sig_was_caught ] ; then
printf "Execution aborted!\n"
exit $saved_status
elif [ $saved_status -ne 0 ] ; then
printf "An error occurred!\n"
exit 8;
fi
}
trap exit_handler EXIT
trap sig_handler HUP INT QUIT TERM
sleep 3; false
If that works, it boils down to whether "set -e" meets the requirements
that you're trying to satisfy with "trap ... ERR".