How to run a command before a Bash script exits?

后端 未结 4 921
感情败类
感情败类 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:07

    From the reference for set:

    -e

    Exit immediately if a simple command (see section 3.2.1 Simple Commands) exits with a non-zero status, unless the command that fails is part of an until or while loop, part of an if statement, part of a && or || list, or if the command's return status is being inverted using !. A trap on ERR, if set, is executed before the shell exits.

    (Emphasis mine).

    0 讨论(0)
  • 2020-12-07 14:09

    Here's an example of using trap:

    #!/bin/bash -e
    
    function cleanup {
      echo "Removing /tmp/foo"
      rm  -r /tmp/foo
    }
    
    trap cleanup EXIT
    mkdir /tmp/foo
    asdffdsa #Fails
    

    Output:

    dbrown@luxury:~ $ sh traptest
    t: line 9: asdffdsa: command not found
    Removing /tmp/foo
    dbrown@luxury:~ $
    

    Notice that even though the asdffdsa line failed, the cleanup still was executed.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-07 14:12

    From the bash manpage (concerning builtins):

    trap [-lp] [[arg] sigspec ...]
    The command arg is to be read and executed when the shell receives signal(s) sigspec.

    So, as indicated in Anon.'s answer, call trap early in the script to set up the handler you desire on ERR.

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