gpt4 book ai didi

bash - bash函数非零退出代码

转载 作者:行者123 更新时间:2023-12-03 08:06:52 25 4
gpt4 key购买 nike

在下面的函数“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

最佳答案

有两个问题:

  • 您在运行handleExit之前先运行wrapper,所以它尚未失败。
  • 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

    关于bash - bash函数非零退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48896130/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com