Shell scripts are handy for automating tasks like backup databases, clearing log files, etc. You need to perform some tasks when the script finishes the execution. No matter at which stage the script is finished.
For example, a script that clears the log files from the system. The script first checks the size of the log file, if the log file size is lower than the specified size, the script exits. In that case, you still want to run a block of code.
To do this, we can use the trap command to catch the EXIT signal and execute a command or function. Below is the sample shell script to run a function or command on shell script exit.
1 2 3 4 5 6 7 8 9 | #!/usr/bin/env bash on_exit(){ echo "Your script ended now" } trap 'on_exit' EXIT echo "Hello world" |
Run the above script and see the results
OutputHello world Your script ended now
Hope, this quick how-to guide helps you to improve your shell script writing skills.