Search⌘ K

Traps and Signals

Explore how traps and signals control process behavior in Bash. Understand signal numbers, trapping techniques, the kill command, and process groups. This lesson helps you handle script termination and interruptions effectively, laying a foundation for advanced Bash scripting.

How Important is this Lesson?

Traps are an advanced concept. If you’re new to bash you might want to follow this lesson to be aware of it, and apply it as you get more knowledge of Linux or go deeper into bash scripting.

Triggering signals

Any easy way to trigger a signal is one you will likely already have used.

Follow the instructions here:

Shell
sleep 999
Terminal 1
Terminal
Loading...

Now hit the CTRL key down, hold it, and then hit the c key (CTRL-c). Then get the exit code:

Shell
echo $?

You should have got the output of a number over 128. You will of course remember that $? is a special variable that gives the exit code of the last-run command.

What you are less likely to have remembered is that exit codes over 128 indicate that a signal triggered the exit, and that to determine the signal number you take 128 away from the number you saw.

Bonus points if you did remember!

Can you work out what the signal was that stopped the sleep command?

The signals are usually documented in the signal man page.

Shell
man signal
man 7 signal

Note: man pages have different sections. man man will explain more if you’re interested, but to get a specific section, you put the section number in the middle, as above. Find out what section 7 is by reading man man. You might not have ...