代码之家  ›  专栏  ›  技术社区  ›  thebiggestlebowski

bash函数非零退出代码

  •  0
  • thebiggestlebowski  · 技术社区  · 8 年前

    在下面的函数“handleExit”中,exitCode为零,即“0”。我希望它是“1”。我的函数名为“退出1”。我需要做什么才能检测到函数“WriteToError”的状态为非零。

    #!/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 回复  |  直到 8 年前
        1
  •  4
  •   that other guy    8 年前

    有两个问题:

    1. 你跑吧 handleExit 跑步前 wrapper ,所以它还没有失败。
    2. handleExit公司 检查的退出代码 echo

    如果没有描述你想做什么,我猜你想要:

    #!/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
    
    推荐文章