Course contentsShow
← Linux
Lesson 77 of 1,8191. Shell Architecture and Process EnvironmentFree lesson

Session Scope and Environment Cleanup

Implement exit hooks to perform cleanup when a terminal session is closed.

In this lesson, you will learn how to ensure your scripts automatically "tidy up" by running cleanup commands the moment your terminal session ends.

Why Cleanup Matters

When you run processes, create temporary files, or acquire locks within a terminal session, those resources can become "orphaned" if you simply close the window or log out. An orphaned lock file might prevent your scripts from running the next time, or a background process might linger, consuming memory. To prevent this, Linux shells provide a built-in mechanism to "trap" the signals sent when a session terminates.

The trap Command

The primary tool for environment cleanup is the trap command. It allows you to define a specific command (or function) that the shell should execute automatically when it receives a termination signal.

When you close a terminal or log out, the shell typically receives an EXIT signal. By "trapping" this signal, you can execute a cleanup routine regardless of whether you exited on purpose or the session was interrupted.

Implementation Example

Consider a script that creates a temporary lock file to prevent multiple instances from running. You want to ensure that if the session closes, the lock file is deleted.

# Define our cleanup function
cleanup() {
    echo "Cleaning up temporary files..."
    rm -f /tmp/my_script.lock
}

# Register the cleanup function to run on EXIT
trap cleanup EXIT

# Your script logic starts here
touch /tmp/my_script.lock
echo "Script is running. Close the terminal to see the cleanup."
sleep 100

In this example, the trap command tells the shell: "If this script ends for any reason, run the cleanup function first."

Even if you force-close the terminal, the shell's session leader responsibilities ensure that the EXIT signal is triggered, allowing your cleanup function to execute before the environment is fully destroyed. This is a robust way to ensure that your environment remains clean and that future sessions aren't impacted by stale state from your previous work.

Key Takeaway: Use the trap command to associate a cleanup function with the EXIT signal, ensuring that temporary resources are reclaimed automatically when a session ends.