Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to execute a command on exit (regardless of how the script exited)?

Tags:

bash

exit

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?

like image 750
imnotfred Avatar asked Mar 06 '13 23:03

imnotfred


People also ask

How do you exit a script command?

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”.

How would you exit a Linux script when any of the commands in the script fails to execute?

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.

What is exit command in shell script?

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.

How do you get the last code out of exit command?

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.


1 Answers

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
like image 143
Martin Avatar answered Nov 18 '22 22:11

Martin