0
0
Bash Scriptingscripting~5 mins

trap for cleanup on exit in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AKeyboard interrupt only
BSystem shutdown
CScript exit (normal or interrupted)
DFile deletion
Which command creates a temporary file in bash?
Atempfile
Bmktemp
Ctouch temp
Dcreatefile
Why use trap to catch signals like INT or TERM?
ATo run cleanup code before the script stops
BTo speed up the script
CTo ignore errors
DTo create new files
What happens if you don’t use trap for cleanup in a script that creates temp files?
AFiles are deleted automatically
BScript runs faster
CScript won’t run
DTemp files may remain and clutter the system
Which of these is a correct way to set a trap for cleanup on exit?
Atrap cleanup EXIT
Btrap EXIT cleanup
Ctrap cleanup SIGINT
Dtrap EXIT
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.