Trap Command and Cleaning Up
Introduction to Trap Command and Cleaning Up
Welcome! In this lesson, we will explore the powerful trap command in Bash. The trap command executes a set of commands when a script exits, whether it completes successfully or encounters an error. This command is crucial for managing cleanup operations in your scripts. Proper cleanup ensures that temporary files and other resources do not clutter your system or cause unexpected behaviors.
Let's get started!
Understanding the trap Command
The trap command in Bash allows you to specify commands that should be executed when a certain signal is received by the script. Signals are notifications sent to a process to notify it of various events. For example, the EXIT signal is sent when the script exits, either normally or due to an error. The INT (interrupt) signal triggers when you press Ctrl+C to interrupt the script.
The general syntax for the trap command in Bash is as follows:
This line instructs the script to run commands when the specified signal is received. commands can be a string of commands, another script or a function.
The following script creates a file called temp.txt then exits. We use the trap command to remove this temporary file once the script exits.
solution.sh
In this script:
- The
cleanupfunction removes temporary files and printslsoutput before and afterrm -f temp.txt. trap cleanup EXIT: Sets up a trap to call thecleanupfunction on script exit.touch temp.txt: Creates an empty file namedtemp.txt.- Two
echostatements simulate work with the temporary file. - When
exit 0is executed, thetrapcommand ensures thecleanupfunction is called to remove the temporary file.
The output of the script is:
The output of the script shows that when the exit 0 command is executed, the cleanup function is called, successfully removing the temp.txt. The trap command ensures that the cleanup function is executed regardless of how the script exits, providing a robust way to manage resources.
