Is EXIT required to run if SIGINT or SIGTERM is 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 how it should work and that it is generally indicated.

+6
source share
1 answer

The EXIT trap does not work the same in every shell. A few examples:

  • In dash and zsh, it only starts by regularly exiting the script.
  • In zsh, if you catch a signal that normally stops executing, you need to restore the default behavior by explicitly calling exit .

I would advise you to actually catch the signals and then exit, it should be portable in 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 
+2
source

Source: https://habr.com/ru/post/978380/


All Articles