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?✗ Incorrect
The
trap command catches signals like Ctrl+C and runs specified commands before the script exits or continues.Which signal is sent when you press Ctrl+C in the terminal?
✗ Incorrect
Ctrl+C sends the SIGINT (interrupt) signal to the running process.
How do you remove a previously set trap in bash?
✗ Incorrect
Using
trap '' SIGNAL removes the trap for that signal.What will this command do?
trap 'echo Exiting' EXIT✗ Incorrect
The EXIT signal runs when the script finishes, so it prints 'Exiting' at the end.
If a script traps SIGTERM and SIGINT with the same command, what happens when either signal is received?
✗ Incorrect
The trap command runs the specified commands for any of the listed 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.