How to run a command before a Bash script exits?

后端 未结 4 945
感情败类
感情败类 2020-12-07 13:44

If a Bash script has set -e, and a command in the script returns an error, how can I do some cleanup before the script exits?

For example:



        
4条回答
  •  悲&欢浪女
    2020-12-07 14:11

    sh version of devguydavid's answer.

    #!/bin/sh
    set -e
    cleanup() {
      echo "Removing /tmp/foo"
      rm  -r /tmp/foo
    }
    trap cleanup EXIT
    mkdir /tmp/foo
    asdffdsa #Fails
    

    ref: shellscript.sh

提交回复
热议问题