villatrans.blogg.se

Clean exit
Clean exit









clean exit clean exit

But not all shells invoke the EXIT handler on SIGINT/ SIGTERM.įor them you can try to set one handler for several signals ( trap '.' INT EXIT), but then it may be invoked several times: $ bash -c 'trap "echo trap" INT EXIT sleep 3' & pid=$! sleep 1 kill -INT $pid wait For bash it's probably okay to just use EXIT. It depends on what you're trying to achieve, and which shells you're targeting. Past experience says if you (like me) always press Ctrl-C several times, you'll sometimes catch it half way through the cleanup part of your shell script, so this works but not always as perfectly as you'd like. So I think it's also worth trapping, even if it's a little obscure. SIGQUIT is Ctrl-\ if you've never tried it. You can't rely on a shellscript getting to the bottom. I trap exit because shell scripts can exit before they reach the bottom - syntax errors, set -e and a nonzero return, simply calling exit. With bash, it seems that exiting in the INT handler also calls the EXIT handler, hence I untrap the exit handler and call it myself (which will work in any shell regardless of behaviour).

Clean exit code#

So I ensure that the cleanup exits afterwards, and in the case of the signals always uses an error code (and in the other case of a normal exit, preserves the error code). INT and TERM handlers don't quit for me when I test - they handle the error then the shell returns to exiting (and this is not too surprising). Trap '' EXIT # some shells will call EXIT after the INT handler Refining the last answer, because it has issues: # Our general exit handler











Clean exit