Bird
Raised Fist0
Bash Scriptingscripting~10 mins

Signal handling with trap in Bash Scripting - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Signal handling with trap
Start script
↓
Set trap for signal
↓
Run main loop or commands
↓
Signal received?
No→Continue running
Yes↓
Execute trap command
↓
Continue or exit script
The script sets a trap to catch signals, runs commands, and when a signal arrives, it runs the trap command before continuing or exiting.
Execution Sample
Bash Scripting
trap "echo 'Signal received, exiting'; exit" SIGINT
while true; do
  echo "Running..."
  sleep 1
done
This script prints 'Running...' every second until you press Ctrl+C, which triggers the trap to print a message and exit.
Execution Table
StepActionSignal ReceivedTrap Command ExecutedOutputScript State
1Start script and set trapNoNoRunning
2Print 'Running...'NoNoRunning...Running
3Sleep 1 secondNoNoRunning
4Print 'Running...'NoNoRunning...Running
5Sleep 1 secondNoNoRunning
6User presses Ctrl+C (SIGINT)YesYesSignal received, exitingExiting
7Exit scriptNoNoExited
💡 User pressed Ctrl+C, SIGINT caught, trap executed, script exited
Variable Tracker
VariableStartAfter 1After 2After SIGINTFinal
Script StateNot startedRunningRunningExitingExited
Key Moments - 3 Insights
Why does the script not exit immediately when started?
Because the trap only runs when the specified signal (SIGINT) is received. Until then, the script keeps running the loop as shown in rows 2-5 of the execution_table.
What happens when Ctrl+C is pressed during the sleep?
The signal SIGINT is sent, the trap command runs (row 6), printing the message and exiting the script immediately.
Can the trap command run multiple times if multiple signals are sent?
Yes, each time the signal is received, the trap command runs. But in this example, the trap exits the script, so it runs only once.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the script state after step 4?
AExiting
BExited
CRunning
DNot started
💡 Hint
Check the 'Script State' column at step 4 in the execution_table
At which step does the trap command execute?
AStep 6
BStep 4
CStep 2
DStep 7
💡 Hint
Look for 'Trap Command Executed' marked 'Yes' in the execution_table
If the trap command did not call exit, what would happen after step 6?
AScript would exit immediately
BScript would continue running the loop
CScript would pause indefinitely
DScript would restart
💡 Hint
Refer to the key_moments explanation about trap behavior without exit
Concept Snapshot
trap "command" SIGNAL
- Sets a command to run when SIGNAL is received
- Commonly used to handle Ctrl+C (SIGINT)
- Allows cleanup or graceful exit
- Script continues unless trap command exits
- Example: trap "echo Exiting; exit" SIGINT
Full Transcript
This visual trace shows how a bash script uses trap to handle signals. The script sets a trap for SIGINT (Ctrl+C). It runs a loop printing 'Running...' every second. When the user presses Ctrl+C, the signal is caught, the trap command runs printing 'Signal received, exiting', then the script exits. Variables like script state change from running to exiting to exited. Key moments include understanding that the trap only runs on signal, and that exit in the trap stops the script. The quiz tests understanding of script state and trap execution steps.

Practice

(1/5)
1. What does the trap command do in a bash script?
easy
A. It creates a loop that repeats commands indefinitely.
B. It catches signals like Ctrl+C and runs specified commands.
C. It defines a function to be used later in the script.
D. It pauses the script until a key is pressed.

Solution

  1. Step 1: Understand the purpose of trap

    The trap command is used to catch signals sent to the script, such as Ctrl+C (SIGINT).
  2. Step 2: What trap does with signals

    When a signal is caught, trap runs the commands specified by the user to handle that signal.
  3. Final Answer:

    It catches signals like Ctrl+C and runs specified commands. -> Option B
  4. Quick Check:

    trap catches signals = B [OK]
Hint: Trap runs commands on signals like Ctrl+C [OK]
Common Mistakes:
  • Thinking trap creates loops
  • Confusing trap with function definition
  • Assuming trap pauses script
2. Which of the following is the correct syntax to run echo "Bye" when the script receives a SIGINT signal?
easy
A. trap 'echo "Bye"' SIGINT
B. trap echo "Bye" SIGINT
C. trap (echo "Bye") SIGINT
D. trap {echo "Bye"} SIGINT

Solution

  1. Step 1: Check trap syntax for commands

    The commands to run must be quoted as a single string, usually with single quotes to preserve special characters.
  2. Step 2: Identify correct quoting style

    trap 'echo "Bye"' SIGINT uses single quotes around the entire command string, which is the correct syntax.
  3. Final Answer:

    trap 'echo "Bye"' SIGINT -> Option A
  4. Quick Check:

    trap 'commands' SIGNAL = A [OK]
Hint: Use single quotes around commands in trap [OK]
Common Mistakes:
  • Not quoting commands properly
  • Using parentheses or braces incorrectly
  • Omitting quotes causing syntax errors
3. What will be the output of this script when you press Ctrl+C during its execution?
#!/bin/bash
trap 'echo "Interrupted! Cleaning up..."; exit' SIGINT
while true; do
  echo "Running..."
  sleep 2
done
medium
A. The script ignores Ctrl+C and keeps running.
B. It crashes with an error message.
C. It prints "Running..." once and then exits.
D. It prints "Interrupted! Cleaning up..." and exits.

Solution

  1. Step 1: Understand trap on SIGINT

    The trap command catches the SIGINT signal (Ctrl+C) and runs the echo and exit commands.
  2. Step 2: Effect of trap during infinite loop

    When Ctrl+C is pressed, the script prints the message and exits immediately, stopping the loop.
  3. Final Answer:

    It prints "Interrupted! Cleaning up..." and exits. -> Option D
  4. Quick Check:

    trap on SIGINT prints message and exits = D [OK]
Hint: trap runs commands on Ctrl+C, then script exits [OK]
Common Mistakes:
  • Thinking script ignores Ctrl+C
  • Assuming loop stops without message
  • Expecting error instead of clean exit
4. Identify the error in this script snippet:
trap echo "Exiting" SIGTERM
sleep 10
medium
A. sleep command cannot be used with trap.
B. SIGTERM is not a valid signal name.
C. Missing quotes around the command to run in trap.
D. trap must be placed after sleep command.

Solution

  1. Step 1: Check trap command syntax

    The command to run on signal must be quoted as a single string to avoid syntax errors.
  2. Step 2: Identify missing quotes

    Here, echo "Exiting" is not quoted, so the shell misinterprets the command.
  3. Final Answer:

    Missing quotes around the command to run in trap. -> Option C
  4. Quick Check:

    trap commands need quotes = C [OK]
Hint: Always quote trap commands to avoid syntax errors [OK]
Common Mistakes:
  • Not quoting trap commands
  • Using invalid signal names
  • Placing trap after commands needing it
5. You want a bash script to delete a temporary file /tmp/mytempfile when it exits, whether normally or due to Ctrl+C. Which trap command correctly achieves this?
hard
A. trap 'rm -f /tmp/mytempfile' EXIT
B. trap 'rm -f /tmp/mytempfile' SIGINT
C. trap 'rm -f /tmp/mytempfile' SIGTERM
D. trap 'rm -f /tmp/mytempfile' SIGINT SIGTERM

Solution

  1. Step 1: Understand EXIT signal

    EXIT is a special trap signal that runs commands when the script ends for any reason, including normal exit or Ctrl+C.
  2. Step 2: Why EXIT is better than SIGINT or SIGTERM alone

    Using EXIT ensures cleanup runs on all script exits, not just specific signals.
  3. Final Answer:

    trap 'rm -f /tmp/mytempfile' EXIT -> Option A
  4. Quick Check:

    Use EXIT to clean up on all exits = A [OK]
Hint: Use trap on EXIT to clean up on any script exit [OK]
Common Mistakes:
  • Using only SIGINT or SIGTERM misses normal exit
  • Not quoting the command
  • Expecting multiple signals needed for all exits
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard