I have a script that writes out to temporary files to aid in its execution. At the end of my script I simply call rm filename
to clean up the temp files I created. The problem is when the script ends due to error or is interrupted. In these cases, the rm
statement is never reached and thus the files are never cleaned up. Is there a way I can specify some command to run on exit regardless of whether or not it was a successful exit?
One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.
Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.
exit-Issuing the exit command at the shell prompt will cause the shell to exit. In some cases, if you have jobs running in the background, the shell will remind you that they are running and simply return you to the command prompt. In this case, issuing exit again will terminate those jobs and exit the shell.
To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.
Yes, you can use trap
like so:
trap "rm -f filename" EXIT
A script could look like this:
#/bin/bash
trap "rm -f filename" EXIT # remove file when script exits
touch filename # create file
some-invalid-command # trigger an error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With