Is there a way to execute the command on exit (no matter how the script ended)?

I have a script that writes temporary files to help in its execution. At the end of my script, I just call the rm filenametemp files I created to clean up. The problem is that the script ends due to an error or is interrupted. In these cases, the statement is rmnever reached, and therefore the files are never cleared. Is there a way to tell some command to run on exit, regardless of whether it was a successful exit?

+5
source share
4 answers

Yes; You can write:

trap 'rm filename' EXIT

(. trap & sect; 4.1 " Bourne" Bash.)

, , — , - SIGKILL Bash, script — , .

+2

, trap :

trap "rm -f filename" EXIT

A script :

#/bin/bash
trap "rm -f filename" EXIT   # remove file when script exits
touch filename               # create file
some-invalid-command         # trigger an error
+2

onintr , , .

0

: script , SIGHUP SIGTERM. , SIGKILL ( ). Google "bash script "

For unsuccessful exit: the structure that you code so that you call the function in rm filename (or just put the statement) before exiting the script

0
source

All Articles