Bird
0
0

Why does this script fail to run cleanup on exit?

medium📝 Debug Q7 of 15
Bash Scripting - Error Handling
Why does this script fail to run cleanup on exit?
#!/bin/bash
trap 'cleanup' EXIT
cleanup() {
  echo "Cleaning up"
}
exit 0
Atrap command is correct, but cleanup is never called
Btrap command syntax is correct and script works as expected
Ctrap command quotes prevent function execution
Dcleanup function is defined after trap, so trap can't find it
Step-by-Step Solution
Solution:
  1. Step 1: Understand function definition and trap timing

    Functions can be defined after trap; trap runs commands on exit regardless.
  2. Step 2: Confirm trap and function behavior

    trap 'cleanup' EXIT runs cleanup on exit, so script prints "Cleaning up" before exit.
  3. Final Answer:

    trap command syntax is correct and script works as expected -> Option B
  4. Quick Check:

    trap runs commands on exit even if function defined later [OK]
Quick Trick: trap runs commands on exit regardless of function order [OK]
Common Mistakes:
MISTAKES
  • Assuming function must be defined before trap
  • Thinking quotes prevent function call
  • Believing cleanup is never called

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes