If a Bash script has set -e
, and a command in the script returns an error, how can I do some cleanup before the script exits?
For example:
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.