Removing created temp files in unexpected bash exit

前端 未结 8 1619
无人及你
无人及你 2021-01-29 21:44

I am creating temporary files from a bash script. I am deleting them at the end of the processing, but since the script is running for quite a long time, if I kill it or simply

相关标签:
8条回答
  • 2021-01-29 22:41

    Just keep in mind that choosen answer is bashism, which means solution as

    trap "{ rm -f $LOCKFILE }" EXIT
    

    would work only in bash (it will not catch Ctrl+c if shell is dash or classic sh), but if you want compatibility then you still need to enumerate all signals that you want to trap.

    Also keep in mind that when script exits the trap for signal "0"(aka EXIT) is always performed resulting in double execution of trap command.

    That the reason not to stack all signals in one line if there is EXIT signal.

    To better understand it look at following script that will work across different systems without changes:

    #!/bin/sh
    
    on_exit() {
      echo 'Cleaning up...(remove tmp files, etc)'
    }
    
    on_preExit() {
      echo
      echo 'Exiting...' # Runs just before actual exit,
                        # shell will execute EXIT(0) after finishing this function
                        # that we hook also in on_exit function
      exit 2
    }
    
    
    trap on_exit EXIT                           # EXIT = 0
    trap on_preExit HUP INT QUIT TERM STOP PWR  # 1 2 3 15 30
    
    
    sleep 3 # some actual code...
    
    exit 
    

    This solution will give you more control since you can run some of your code on occurrence of actual signal just before final exit (preExit function) and if it needed you can run some code at actual EXIT signal (final stage of exit)

    0 讨论(0)
  • 2021-01-29 22:41

    The alternative of using a predictable file name with $$ is a gaping security hole and you should never, ever, ever think about using it. Even if it is just a simple personal script on your single user PC. It is a very bad habit you should not obtain. BugTraq is full of "insecure temp file" incidents. See here, here and here for more information on the security aspect of temp files.

    I was initially thinking of quoting the insecure TMP1 and TMP2 assignments, but on second thought that would probably not be a good idea.

    0 讨论(0)
提交回复
热议问题