BashMultipleTraps

22nd September 2016 at 10:50am
Bash CodeSnippets
nicolaw@nicolaw:~ $ ./traps.sh
+ TRAPS=()
+ declare -ax TRAPS
+ trap run_trap_handlers EXIT INT USR1 USR2 TERM HUP
+ TRAPS+=("handler_1" "handler_2")
+ sleep 1
+ [[ 3 -eq 1 ]]
+ sleep 1
+ [[ 1 -eq 1 ]]
+ ls /path/that/does/not/exist
ls: cannot access /path/that/does/not/exist: No such file or directory
+ run_trap_handlers
+ local -i RC=2
+ for handler in '"${TRAPS[@]}"'
+ handler_1
+ caller
10 ./traps.sh
+ echo '$RC=2'
$RC=2
+ for handler in '"${TRAPS[@]}"'
+ handler_2
+ caller
10 ./traps.sh
+ echo 'Hello world'
Hello world
nicolaw@nicolaw:~ $
#!/bin/bash

set -euxo pipefail

declare -ax TRAPS=()

run_trap_handlers () {
    local -i RC=$?
    for handler in "${TRAPS[@]}" ; do
        $handler "$@"
    done
}

trap run_trap_handlers EXIT INT USR1 USR2 TERM HUP

handler_1 () {
    caller
    echo "\$RC=$RC"
}

handler_2 () {
    caller
    echo "Hello world"
}

TRAPS+=("handler_1" "handler_2")

while sleep 1 ; do
    [[ ${RANDOM::1} -eq 1 ]] && ls /path/that/does/not/exist
done