Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a command before a Bash script exits?

Tags:

bash

People also ask

Does a bash script wait for command to finish?

The bash wait command is a Shell command that waits for background running processes to complete and returns the exit status. Unlike the sleep command, which waits for a specified time, the wait command waits for all or specific background tasks to finish.

How do I exit bash script without exiting shell?

If you are executing a Bash script in your terminal and need to stop it before it exits on its own, you can use the Ctrl + C combination on your keyboard. A ^C character will appear in your terminal to indicate a keyboard interrupt.

What is CTRL C in bash?

When you hit Ctrl + c , the line discipline of your terminal sends SIGINT to processes in the foreground process group. Bash, when job control is disabled, runs everything in the same process group as the bash process itself. Job control is disabled by default when Bash interprets a script.


Here's an example of using trap:

#!/bin/bash -e

function cleanup {
  echo "Removing /tmp/foo"
  rm  -r /tmp/foo
}

trap cleanup EXIT
mkdir /tmp/foo
asdffdsa #Fails

Output:

dbrown@luxury:~ $ sh traptest
t: line 9: asdffdsa: command not found
Removing /tmp/foo
dbrown@luxury:~ $

Notice that even though the asdffdsa line failed, the cleanup still was executed.


From the bash manpage (concerning builtins):

trap [-lp] [[arg] sigspec ...]
The command arg is to be read and executed when the shell receives signal(s) sigspec.

So, as indicated in Anon.'s answer, call trap early in the script to set up the handler you desire on ERR.


From the reference for set:

-e

Exit immediately if a simple command (see section 3.2.1 Simple Commands) exits with a non-zero status, unless the command that fails is part of an until or while loop, part of an if statement, part of a && or || list, or if the command's return status is being inverted using !. A trap on ERR, if set, is executed before the shell exits.

(Emphasis mine).


sh version of devguydavid's answer.

#!/bin/sh
set -e
cleanup() {
  echo "Removing /tmp/foo"
  rm  -r /tmp/foo
}
trap cleanup EXIT
mkdir /tmp/foo
asdffdsa #Fails

ref: shellscript.sh