bash 在bash脚本中,如何在while循环条件下调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27674687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:05:00  来源:igfitidea点击:

In bash script, how to call function in while loop condition

linuxbashshellsh

提问by Krishna M

Below is my shell script. How to compare the exit status of function in while loop condition block ? Whatever I return from check1function my code enters into while loop

下面是我的shell脚本。如何比较while循环条件块中函数的退出状态?无论我从check1函数返回什么,我的代码都会进入 while 循环

#!/bin/sh
    check1()
    {
            return 1
    }

    while [ check1 ]
    do
            echo $?
            check1
            if [ $? -eq 0 ]; then
                    echo "Called"
            else
                    echo "DD"
            fi
            sleep 5
    done

回答by cdarke

Remove the testcommand - also known as [. So:

删除test命令 - 也称为[. 所以:

while check1
do
    # Loop while check1 is successful (returns 0)

    if check1
    then
        echo 'check1 was successful'
    fi

done

Shells derived from the Bourne and POSIX shells execute a commandafter a conditional statement. One way to look at it is that whileand iftest for success or failure, rather than true or false (although trueis considered successful).

从 Bourne 和 POSIX shell 派生的 shell在条件语句之后执行命令。看它的方法之一是whileif测试成功或失败,而不是真的还是假的(虽然true被认为是成功的)。

By the way, if you must test $?explicitly (which is not often required) then (in Bash) the (( ))construct is usually easier to read, as in:

顺便说一句,如果您必须$?显式测试(这通常不是必需的),那么(在 Bash 中)该(( ))构造通常更易于阅读,如下所示:

if (( $? == 0 ))
then
    echo 'worked'
fi

回答by Fernando

The value returned by a function (or command) execution is stored in $?, one solution would be:

函数(或命令)执行返回的值存储在 $? 中,一种解决方案是:

check1
while [ $? -eq 1 ]
do
    # ...
    check1
done

A nicer and simpler solution may be:

一个更好更简单的解决方案可能是:

while ! check1
do
    # ...
done

In this form zero is true and non-zero is false, for example:

在这种形式中,零为真,非零为假,例如:

# the command true always exits with value 0
# the next loop is infinite
while true
    do
    # ...

You can use !to negate the value:

您可以使用!否定该值:

# the body of the next if is never executed
if ! true
then
    # ...