我在 bash 中有这个函数,其中 if 语句直到范围结束时才会运行,但只运行 if 语句之后的第一个命令,然后继续 first-next 命令之后范围的尽头。我似乎无法弄清楚为什么会发生这种情况,或者为什么一开始就可能发生这种情况。
有问题的代码:
function log() {
if [[ "x$disablelog" != "xtrue" && "x$logfile" != "x" ]]; then
if [[ ! -w "$logfile" ]]; then
touch "$logfile" &>/dev/null
if [[ "$?" != "0" ]]; then
debugout "Cannot write log file $logfile, disabling log."
disablelog="true"
echo "This, and the lines above/below are never executed. However, debugout is."
return 1
fi
fi
echo "[$(date +%s)] $@" >> "$logfile"
fi
}
我过去遇到过几次这个问题,但一直找不到任何相关信息,我想一劳永逸地找出我做错了什么。
更新:根据要求添加调试:
function debugout() {
if [[ "x$debug" != "xtrue" ]]; then
return
fi
if [[ "x$color" == "xtrue" ]]; then
echo -e "\e[1;36mDEBUG:\e[0m $@"
else
echo -e "DEBUG: $@"
fi
log "DEBUG: $@"
}
当我只使用普通 echo 或任何其他命令时,也会发生同样的事情。 (编辑:显然不是...)
最佳答案
debugout
后没有任何东西运行这一事实表明问题就出在这里。
debugout
和log
递归调用,在debugout
调用点后阻止执行。
关于linux - Bash:嵌套的 if 语句没有完成作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16984523/