0
0
Bash Scriptingscripting~5 mins

Signal handling with trap in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the trap command in bash scripting?
The trap command lets a script catch signals (like Ctrl+C) and run specific commands before exiting or continuing. It helps scripts handle interruptions safely.
Click to reveal answer
beginner
How do you use trap to run a cleanup function when the script receives a SIGINT (Ctrl+C)?
You write: trap cleanup_function SIGINT. This means when the script gets SIGINT, it runs cleanup_function before stopping.
Click to reveal answer
beginner
What happens if you don’t use trap and press Ctrl+C during a bash script?
The script stops immediately without running any cleanup. This might leave temporary files or processes running.
Click to reveal answer
intermediate
Explain the syntax of the trap command.
The syntax is: trap 'commands' SIGNALS. You put the commands to run in quotes, then list one or more signals to catch.
Click to reveal answer
intermediate
Can trap handle multiple signals at once? How?
Yes. You list multiple signals after the commands, like: trap 'echo Signal caught' SIGINT SIGTERM. The commands run if any listed signal occurs.
Click to reveal answer
What does the trap command do in a bash script?
ACatches signals and runs commands before exiting
BStarts a new background process
CCreates a new file
DChanges file permissions
Which signal is sent when you press Ctrl+C in the terminal?
ASIGINT
BSIGKILL
CSIGHUP
DSIGTERM
How do you remove a previously set trap in bash?
Atrap - SIGNAL
Btrap '' SIGNAL
Ctrap reset SIGNAL
Dtrap clear SIGNAL
What will this command do? trap 'echo Exiting' EXIT
APrint 'Exiting' when Ctrl+C is pressed
BRestart the script
CIgnore all signals
DPrint 'Exiting' when the script ends
If a script traps SIGTERM and SIGINT with the same command, what happens when either signal is received?
AThe command runs only for SIGINT
BThe command runs only for SIGTERM
CThe command runs for both signals
DThe script ignores both signals
Describe how to use the trap command to handle a signal and why it is useful in bash scripts.
Think about what happens when you press Ctrl+C and how trap can help.
You got /4 concepts.
    Explain what happens if a bash script does not use trap and receives an interrupt signal.
    Consider what happens when you stop a program suddenly.
    You got /3 concepts.