复合条件在 bash while 循环中



我修改了现有的 bash 脚本,并且在使 while 循环行为正常时遇到了一些问题。这是原始代码

while ! /usr/bin/executable1
do
    # executable1 returned an error. So sleep for some time try again
    sleep 2
done

我想将其更改为以下内容

while ! /usr/bin/executable1 && ! $(myfunc)
do
    # executable1 and myfunc both were unsuccessful. So sleep for some time
    sleep 2
done
可执行文件 1 在成功时返回

0,在失败时返回 1。我知道 bash 中的"true"计算结果为 0,这就是为什么原始脚本会继续循环直到可执行文件返回成功的原因

因此,myfunc 是这样编码的

myfunc ()
{
    # Check if file exists. If exits, return 0, If not, return 1
    if [ -e someFile ]; then
        return 0
    fi
    return 1 
 }

我注意到我的新 while 循环似乎没有调用可执行文件 1。它总是调用 myfunc(),然后立即退出循环。我做错了什么?

我尝试了各种编码 while 循环的方法(使用 (( ))、[ ]、[[ ]] 等),但似乎没有什么可以解决它

调用函数不需要$(...),只需捕获其标准输出即可。你只是想要

while ! /usr/bin/executable1 && ! myfunc
do
    sleep 2
done

请注意,myfunc也可以更简单地编写

myfunc () {
    [ -e someFile ]
}

甚至(bash

myfunc () [[ -e someFile ]]

无论哪种方式,几乎都不值得单独定义myfunc;只需使用

while ! /usr/bin/executable1 && ! [[ -e someFile ]]
do
    sleep 2
done

使用 until 循环也可能更简单:

until /usr/bin/executable1 || [[ -e someFile ]]; do
    sleep 2
done

最新更新