0
0
Bash Scriptingscripting~20 mins

trap for cleanup on exit in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Trap Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2: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
ATemporary file created: /tmp/tmp.abcd1234\nCleaning up /tmp/tmp.abcd1234
BTemporary file created: /tmp/tmp.abcd1234
CCleaning up /tmp/tmp.abcd1234
DNo output
Attempts:
2 left
💡 Hint
The trap command runs the cleanup command when the script exits.
💻 Command Output
intermediate
2: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
ACleaning up /tmp/tmp.abcd1234
BTemporary file created: /tmp/tmp.abcd1234
CTemporary file created: /tmp/tmp.abcd1234\nCleaning up /tmp/tmp.abcd1234
DNo output
Attempts:
2 left
💡 Hint
The EXIT trap runs even if the script is interrupted.
📝 Syntax
advanced
2: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?
Atrap rm -f $tmpfile EXIT
Btrap {rm -f $tmpfile} EXIT
Ctrap (rm -f $tmpfile) EXIT
Dtrap 'rm -f $tmpfile' EXIT
Attempts:
2 left
💡 Hint
trap requires a quoted command string as the first argument.
🔧 Debug
advanced
2: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
ABecause the trap is set only for SIGINT, not EXIT, so normal exit skips cleanup
BBecause $tmpfile is empty inside the trap command
CBecause sleep prevents trap from running
DBecause trap commands cannot remove files
Attempts:
2 left
💡 Hint
EXIT trap runs on any exit, SIGINT only on Ctrl+C.
🚀 Application
expert
3: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?
Atrap 'rm -f "$tmpfile"' EXIT; trap 'exit' SIGTERM
Btrap 'rm -f "$tmpfile"' EXIT; trap 'rm -f "$tmpfile"' SIGTERM
Ctrap 'rm -f "$tmpfile"' EXIT SIGTERM
Dtrap 'rm -f "$tmpfile"' SIGTERM
Attempts:
2 left
💡 Hint
You can set multiple traps for different signals.