Removing created temp files in unexpected bash exit

前端 未结 8 1623
无人及你
无人及你 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条回答
  •  -上瘾入骨i
    2021-01-29 22:31

    You want to use the trap command to handle exiting the script or signals like CTRL-C. See the Greg's Wiki for details.

    For your tempfiles, using basename $0 is a good idea, as well as providing a template that provides room for enough temp files:

    tempfile() {
        tempprefix=$(basename "$0")
        mktemp /tmp/${tempprefix}.XXXXXX
    }
    
    TMP1=$(tempfile)
    TMP2=$(tempfile)
    
    trap 'rm -f $TMP1 $TMP2' EXIT
    

提交回复
热议问题