bash函数非零退出代码

时间:2018-02-20 23:55:08

标签: bash error-handling exit

在下面的函数“handleExit”中,exitCode为零,即“0”。我希望它是“1”。我的功能称为“退出1”。为了检测函数“writeToErr”是否具有非零状态,我需要做什么。

#!/bin/bash

set -euo pipefail

logError() {
  awk " BEGIN { print \"$@\" > \"/dev/fd/2\" }"
}

function writeToErr ()  {
    echo "standard out"
    logError "standard err"
    exit 1
}

function wrapper () {
    writeToErr >>output.log 2>&1
}

function handleExit () {
    echo "handle exit"
    exitCode=$?
    if [ $exitCode -eq "0" ]
     then
        echo "No problem"
     else
        echo "$0 exited unexpectedly with status:$exitCode"
        exit 1
     fi
}

trap wrapper EXIT
handleExit >>output.log 2>&1

以下是“output.log”的内容:

handle exit
No problem
standard out
standard err

1 个答案:

答案 0 :(得分:3)

有两个问题:

  1. 您在运行handleExit之前运行wrapper,因此它还没有失败。
  2. handleExit检查echo
  3. 的退出代码

    如果没有您想要做的事情的描述,我猜猜你想要:

    #!/bin/bash
    
    set -euo pipefail
    
    logError() {
        # A better way to write to stderr
        echo "$*" >&2
    }
    
    function writeToErr ()  {
        echo "standard out"
        logError "standard err"
        exit 1
    }
    
    function wrapper () {
        writeToErr >>output.log 2>&1
    }
    
    function handleExit () {
        # Get exit code of the previous command, instead of echo
        exitCode=$?
        echo "handle exit"
        if [ $exitCode -eq "0" ]
         then
            echo "No problem"
         else
            echo "$0 exited unexpectedly with status:$exitCode"
            exit 1
         fi
    }
    
    # Call handler on exit, so it has something to handle
    trap handleExit EXIT
    wrapper