Bird
0
0

You want to ensure temporary files are deleted when your script exits, even if interrupted. Which trap setup is best?

hard🚀 Application Q8 of 15
Bash Scripting - Error Handling
You want to ensure temporary files are deleted when your script exits, even if interrupted. Which trap setup is best?
Atrap 'rm -f /tmp/mytempfile' EXIT SIGINT SIGTERM
Btrap 'rm -f /tmp/mytempfile' EXIT
Ctrap 'rm -f /tmp/mytempfile' SIGKILL
Dtrap 'rm -f /tmp/mytempfile' SIGSTOP
Step-by-Step Solution
Solution:
  1. Step 1: Identify signals to trap for cleanup

    EXIT runs on normal exit, SIGINT and SIGTERM cover interrupts and termination.
  2. Step 2: Choose trap covering all exit cases

    trap 'rm -f /tmp/mytempfile' EXIT SIGINT SIGTERM traps EXIT, SIGINT, and SIGTERM to delete temp file in all cases.
  3. Final Answer:

    trap 'rm -f /tmp/mytempfile' EXIT SIGINT SIGTERM -> Option A
  4. Quick Check:

    Trap multiple signals to ensure cleanup on exit and interrupts [OK]
Quick Trick: Trap EXIT, SIGINT, SIGTERM for reliable cleanup [OK]
Common Mistakes:
MISTAKES
  • Trying to trap SIGKILL or SIGSTOP which cannot be trapped
  • Only trapping EXIT misses interrupts
  • Not quoting commands in trap

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes