What if your script could clean up after itself every time you stop it suddenly?
Why Signal handling with trap in Bash Scripting? - Purpose & Use Cases
Imagine you are running a long script in the terminal, and suddenly you need to stop it safely or clean up temporary files before exiting. Without any special setup, you just press Ctrl+C and hope nothing breaks.
Manually stopping scripts can leave your system messy or your data corrupted. You might forget to remove temporary files or close connections, causing errors later. It's slow and risky to handle these interruptions by hand every time.
Using trap in bash lets your script catch signals like Ctrl+C and run cleanup code automatically. This means your script can stop safely, remove temporary files, and leave things tidy without you doing anything extra.
echo 'Running...'; sleep 100; echo 'Done'
trap 'echo Cleanup; rm -f temp.txt; exit' INT; echo 'Running...'; sleep 100; echo 'Done'
You can make your scripts smart and safe by handling interruptions gracefully, avoiding errors and wasted time.
When downloading files or processing data, if you press Ctrl+C, the script can delete partial files and close connections properly, so you don't get broken or incomplete results.
Manual interruption can cause messy leftovers and errors.
trap lets scripts catch signals and run cleanup code.
This makes scripts safer and more reliable during unexpected stops.
Practice
trap command do in a bash script?Solution
Step 1: Understand the purpose of trap
The trap command is used to catch signals sent to the script, such as Ctrl+C (SIGINT).Step 2: What trap does with signals
When a signal is caught, trap runs the commands specified by the user to handle that signal.Final Answer:
It catches signals like Ctrl+C and runs specified commands. -> Option BQuick Check:
trap catches signals = B [OK]
- Thinking trap creates loops
- Confusing trap with function definition
- Assuming trap pauses script
echo "Bye" when the script receives a SIGINT signal?Solution
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.Step 2: Identify correct quoting style
trap 'echo "Bye"' SIGINT uses single quotes around the entire command string, which is the correct syntax.Final Answer:
trap 'echo "Bye"' SIGINT -> Option AQuick Check:
trap 'commands' SIGNAL = A [OK]
- Not quoting commands properly
- Using parentheses or braces incorrectly
- Omitting quotes causing syntax errors
#!/bin/bash trap 'echo "Interrupted! Cleaning up..."; exit' SIGINT while true; do echo "Running..." sleep 2 done
Solution
Step 1: Understand trap on SIGINT
The trap command catches the SIGINT signal (Ctrl+C) and runs the echo and exit commands.Step 2: Effect of trap during infinite loop
When Ctrl+C is pressed, the script prints the message and exits immediately, stopping the loop.Final Answer:
It prints "Interrupted! Cleaning up..." and exits. -> Option DQuick Check:
trap on SIGINT prints message and exits = D [OK]
- Thinking script ignores Ctrl+C
- Assuming loop stops without message
- Expecting error instead of clean exit
trap echo "Exiting" SIGTERM sleep 10
Solution
Step 1: Check trap command syntax
The command to run on signal must be quoted as a single string to avoid syntax errors.Step 2: Identify missing quotes
Here, echo "Exiting" is not quoted, so the shell misinterprets the command.Final Answer:
Missing quotes around the command to run in trap. -> Option CQuick Check:
trap commands need quotes = C [OK]
- Not quoting trap commands
- Using invalid signal names
- Placing trap after commands needing it
/tmp/mytempfile when it exits, whether normally or due to Ctrl+C. Which trap command correctly achieves this?Solution
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.Step 2: Why EXIT is better than SIGINT or SIGTERM alone
Using EXIT ensures cleanup runs on all script exits, not just specific signals.Final Answer:
trap 'rm -f /tmp/mytempfile' EXIT -> Option AQuick Check:
Use EXIT to clean up on all exits = A [OK]
- Using only SIGINT or SIGTERM misses normal exit
- Not quoting the command
- Expecting multiple signals needed for all exits
Ready to prove it?
Pass the test and this pattern moves unknown
