Bash – how to run custom commands at script exit

Bash scripts can trap EXIT signal and run clean up commands before exit. This is useful if a user kills a script or the script gets killed on its own due to errors. Here is sample code to which traps EXIT signal and calls a custom function onexit.

## Use set -e to exit on error
set -e
function onexit() {
  echo "In onexit function"
trap onexit EXIT
echo "Before calling non_existing_command"
echo "After calling non_existing_command"
Before calling non_existing_command
In onexit function
Env: GNU bash, version 4.3.11
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments