19 March 2014

Unsetting a trap

Quick one: catching a trap in bash is fairly easy with bash' trap command (search for 'trap \[' in bash' man page) but how to clear a set one?
It's in the man page, of course, but who reads those, right? I'm betting the answer is bound to be found on some blog through Google in 0.76 seconds flat ;)
"If arg is absent (and there is a single sigspec) or -, each specified signal is reset to its original disposition (the value it had upon entrance to the shell)."
So it turns out it's fairly simple and this demonstrates it:
root@mgmtsrv:~# cat test.sh
#!/bin/bash
trap 'echo TRAPPED!; break' SIGINT
while [ True ]; do
        sleep 1
done
echo 'end of script'
exit 0
root@mgmtsrv:~# ./test.sh
^CTRAPPED!
end of script
root@mgmtsrv:~#
Now, let's unset the trap:

root@mgmtsrv:~# cat test.sh
#!/bin/bash
trap 'echo TRAPPED!; break' SIGINT
while [ True ]; do
        sleep 1
done
trap - SIGINT
while [ True ]; do
        sleep 1
done
echo 'end of script'
exit 0
root@mgmtsrv:~# ./test.sh
^CTRAPPED!
^C
root@mgmtsrv:~#
So, in short: the 'trap - SIGINT' line clears the set trap :)