Recall & Review
beginner
What does the
trap command do in bash scripting?The
trap command lets you run a specific command or script when the shell receives certain signals or when the script exits. It is often used to clean up temporary files or reset settings.Click to reveal answer
beginner
How do you use
trap to run a cleanup function when a script exits?You write a cleanup function and then use
trap cleanup EXIT. This means the cleanup function runs automatically when the script finishes or is interrupted.Click to reveal answer
intermediate
Why is it useful to trap the
EXIT signal in a script?Trapping
EXIT ensures that cleanup code runs no matter how the script ends, whether normally or due to an error or interruption. This helps keep your system clean and avoids leftover temporary files.Click to reveal answer
intermediate
What happens if you trap signals like
INT or TERM in a script?Trapping
INT (interrupt) or TERM (terminate) lets your script handle those signals gracefully, such as cleaning up before exiting instead of stopping immediately.Click to reveal answer
beginner
Show a simple example of a bash script that creates a temp file and deletes it on exit using
trap.Example:
#!/bin/bash
tempfile=$(mktemp)
echo "Temp file created: $tempfile"
cleanup() {
echo "Removing temp file"
rm -f "$tempfile"
}
trap cleanup EXIT
# Script work here
sleep 5
Click to reveal answer
What signal does
trap cleanup EXIT catch in a bash script?✗ Incorrect
The EXIT signal triggers when the script ends for any reason, normal or interrupted.
Which command creates a temporary file in bash?
✗ Incorrect
mktemp safely creates a unique temporary file.
Why use
trap to catch signals like INT or TERM?✗ Incorrect
Trapping these signals lets the script clean up before exiting.
What happens if you don’t use
trap for cleanup in a script that creates temp files?✗ Incorrect
Without cleanup, temporary files can stay and waste space.
Which of these is a correct way to set a trap for cleanup on exit?
✗ Incorrect
The syntax is trap <command> <signal>, so trap cleanup EXIT is correct.
Explain how the
trap command helps with cleanup in bash scripts.Think about what happens when a script ends or is interrupted.
You got /5 concepts.
Describe a simple bash script scenario where trapping
EXIT is important and what it does.Imagine you create a file that should be deleted no matter how the script ends.
You got /4 concepts.