linux - Bash:嵌套的 if 语句没有完成作用域

标签 linux bash shell if-statement

我在 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 后没有任何东西运行这一事实表明问题就出在这里。

debugoutlog 递归调用,在debugout 调用点后阻止执行。

关于linux - Bash:嵌套的 if 语句没有完成作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16984523/

相关文章:

linux - 在 linux 中执行指定命令时触发警报

PHP - 创建随机哈希字符串以进行电子邮件闭环验证

linux - 仅使用 awk 或其他文件处理实用程序处理文件的 UNIX(AIX) 脚本

bash - 在 Ubuntu 上运行外部工具 - Intellij 作为 sh 文件 - 找不到命令

regex - Bash:逐行遍历文件,找到特定的字符串并附加到每个后续行,直到找到相同的字符串

linux - 仅在下面的目录中查找和复制同名文件并复制到不同的目录

Linux 内核 defconfig 选项不在使用 BuildRoot 的结果 .config 中

c++ - 运行程序时如何捕获输入和输出到文件?

linux - 与 linux shell 有关的参数和选项之间的区别

c - 术语帽 : Get cursor position