Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is trap EXIT required to execute in case of SIGINT or SIGTERM received?

I have a simple script

trap 'echo exit' EXIT
while true; do sleep 1; done

and it behaves differently in different shells:

$ bash tst.sh
^Cexit
$ dash tst.sh
^C
$ zsh tst.sh
^C
$ sh tst.sh
^Cexit

So I'm not sure about how it should operate and whether it is specified at all.

like image 763
Ixanezis Avatar asked Nov 19 '14 09:11

Ixanezis


1 Answers

EXIT trap isn't working the same way in every shell. A few examples:

  • In dash and zsh it's only triggered by a regular exit from within the script.
  • In zsh, if you trap a signal that would normally quit the execution, you need to restore the default behaviour by explicitly calling exit.

I'd suggest you to actually catch the signals and then exit, it should be portable across most shells:

$ cat trap
trap 'echo exit; exit' INT TERM  # and other signals
while true; do sleep 1; done
$ bash trap
^Cexit
$ dash trap
^Cexit
$ zsh trap
^Cexit
$ ksh trap
^Cexit
$ mksh trap
^Cexit
$ busybox sh trap
^Cexit
like image 100
izabera Avatar answered Oct 09 '22 18:10

izabera