bash 函数非零退出代码
bash function non-zero exit code
在下面的函数"handleExit"中,exitCode为零,即“0”。我希望它是“1”。我的函数名为 "exit 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 "[=11=] 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 "[=10=] exited unexpectedly with status:$exitCode"
exit 1
fi
}
# Call handler on exit, so it has something to handle
trap handleExit EXIT
wrapper
在下面的函数"handleExit"中,exitCode为零,即“0”。我希望它是“1”。我的函数名为 "exit 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 "[=11=] 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 "[=10=] exited unexpectedly with status:$exitCode"
exit 1
fi
}
# Call handler on exit, so it has something to handle
trap handleExit EXIT
wrapper