How to run a command on bash script exits

Channel: Linux
Abstract: /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 Output/usr/

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.

#!/usr/bin/env bash on_exit(){ echo "Your script ended now" } trap 'on_exit' EXIT echo "Hello world"123456789#!/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

Output
Hello world
Your script ended now

Hope, this quick how-to guide helps you to improve your shell script writing skills.

Ref From: tecadmin

Related articles