Index

Table of contents

trap

general form
trap [command] [signal]+
empty command to ignore signals completely
trap '' [signal]+
list signals
trap -l
print active traps
trap -p
remove traps
trap - [signal]+
pseudo signals
DEBUG = call before every control flow statement
EXIT = call on exit from shell
ERR = call on non-zero status code (unless in control flow checks)
RETURN = call on function return or after sourcing files

examples

run code on signal 1 (SIGHUP)
trap 'echo "SIGHUP detected in $0"' 1
send SIGHUP
kill -1 [pid]
run code on ctrl-c
trap 'echo "ctrl-c detected in $0"' 2
on ctrl-c ignore signal and keep script running
trap '' 2
run code on ctrl-\
trap 'echo "ctrl-\ detected in $0"' 3
run code on script exit
trap 'echo "bye bye!"' EXIT
call function on ctrl-c
shutdown() {
    echo "shutting down"
    exit 0
}
trap 'shutdown' INT
call function on script exit
function cleanup {
	echo "code goes here"
}
trap cleanup EXIT
multiple statements possible
trap 'echo "bye"; echo "bye"; echo "!"' EXIT

documentation

tutorial
https://developer.ibm.com/articles/au-usingtraps/
manual page
https://www.unix.com/man-page/linux/1/trap/