Challenge - 5 Problems
Trap Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
What is the output when the script exits?
Consider this Bash script that sets a trap to clean up a temporary file on exit. What will be printed when the script finishes?
Bash Scripting
#!/bin/bash tmpfile=$(mktemp) trap 'echo "Cleaning up $tmpfile"; rm -f "$tmpfile"' EXIT echo "Temporary file created: $tmpfile" exit 0
Attempts:
2 left
💡 Hint
The trap command runs the cleanup command when the script exits.
✗ Incorrect
The trap on EXIT runs the echo and rm commands when the script finishes, so both lines print.
💻 Command Output
intermediate2:00remaining
What happens if the script is interrupted with Ctrl+C?
Given this Bash script, what output will appear if the user presses Ctrl+C during the sleep?
Bash Scripting
#!/bin/bash tmpfile=$(mktemp) trap 'echo "Cleaning up $tmpfile"; rm -f "$tmpfile"' EXIT echo "Temporary file created: $tmpfile" sleep 10 exit 0
Attempts:
2 left
💡 Hint
The EXIT trap runs even if the script is interrupted.
✗ Incorrect
When Ctrl+C interrupts the script, the EXIT trap runs, printing the cleanup message and removing the file.
📝 Syntax
advanced2:00remaining
Which trap command correctly cleans up on script exit?
You want to run a cleanup command when the script exits. Which trap syntax is correct?
Attempts:
2 left
💡 Hint
trap requires a quoted command string as the first argument.
✗ Incorrect
trap 'commands' SIGNAL expects the commands as a quoted string. Options A, C, D are invalid syntax.
🔧 Debug
advanced2:00remaining
Why does this trap not run the cleanup command?
This script tries to clean up a file on exit but the cleanup command never runs. Why?
Bash Scripting
#!/bin/bash tmpfile=$(mktemp) trap 'rm -f $tmpfile' SIGINT echo "Temporary file: $tmpfile" sleep 5 exit 0
Attempts:
2 left
💡 Hint
EXIT trap runs on any exit, SIGINT only on Ctrl+C.
✗ Incorrect
The trap is set only for SIGINT (Ctrl+C). If the script exits normally, the trap does not run.
🚀 Application
expert3:00remaining
How to ensure cleanup runs even if script is killed by SIGTERM?
You want your Bash script to always remove a temporary file on exit, even if killed by SIGTERM. Which trap commands should you use?
Attempts:
2 left
💡 Hint
You can set multiple traps for different signals.
✗ Incorrect
EXIT trap runs on normal exit, but SIGTERM kills immediately unless trapped separately. Setting both traps ensures cleanup.