← Back to Bash Course | Chapter 10: Text Processing Tools | Lesson 8 of 12

trap

trap is like setting a safety net that goes off when something surprising happens, such as someone pressing Ctrl+C, so your script can tidy up before it leaves.

In this page:

  1. trap
Syntax
bash
trap 'commands_or_function' SIGNAL

trap

trap registers a command or function to run when the script receives a specific signal, like SIGINT (Ctrl+C) or EXIT (whenever the script ends, for any reason).

trap cleanup EXIT is a common pattern to guarantee cleanup code always runs. Traps are essential for writing scripts that clean up temp files or background jobs reliably.

Note: trap cmd EXIT runs on every exit path — normal completion, an error, or a signal — making it ideal for guaranteed cleanup.

Example: trap

bash
#!/bin/bash
cleanup() {
    echo "Cleaning up before exit..."
}

trap cleanup EXIT

echo "Doing some work..."
echo "Script is about to finish"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trapping signals that cannot be caught, such as SIGKILL.
  2. Forgetting to quote the trap command, so it expands too early.
  3. Not exiting inside a trap for SIGINT, so the script continues after Ctrl+C.
🔒

Chapter Quiz — Complete all 12 topics to unlock

0/12 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.