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

trap

In this page:

  1. trap

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"
🔒

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.