Bash get exit status of command when 'set -e' is active?

前端 未结 4 1455
暗喜
暗喜 2020-12-25 09:55

I generally have -e set in my Bash scripts, but occasionally I would like to run a command and get the return value.

Without doing the set +e; som

4条回答
  •  春和景丽
    2020-12-25 10:02

    From the bash manual:

    The shell does not exit if the command that fails is [...] part of any command executed in a && or || list [...].

    So, just do:

    #!/bin/bash
    
    set -eu
    
    foo() {
      # exit code will be 0, 1, or 2
      return $(( RANDOM % 3 ))
    }
    
    ret=0
    foo || ret=$?
    echo "foo() exited with: $ret"
    

    Example runs:

    $ ./foo.sh
    foo() exited with: 1
    $ ./foo.sh
    foo() exited with: 0
    $ ./foo.sh
    foo() exited with: 2
    

    This is the canonical way of doing it.

提交回复
热议问题