Skip to content

trap

list of signals
$ trap -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL   5) SIGTRAP
 6) SIGABRT  7) SIGBUS   8) SIGFPE   9) SIGKILL 10) SIGUSR1
 ...
 ...
basic syntax
trap [action] [signal]
enable/disable trap
trap "" SIGINT  # enable trap
# uninterruptable magic bash scripting

trap - SIGINT   # disable trap
# interruptable magic bash scripting
clean up on any exit (signal or completion)
TMP_FILE=$(mktemp)
trap "rm -f $TMP_FILE" EXIT

# magic bash scripting
clean up with function
function cleanup {
     # cleanup code
}
trap cleanup EXIT

# magic bash scripting
disable ctrl-c
function no_ctrlc {
    echo "ctrl-c is disabled"
}
trap no_ctrlc SIGINT

while true; do
    sleep 10
done

last updated: Sat Aug 12 14:29:24 2023

Back to top