简体   繁体   English

在bash脚本中,如何在while循环条件下使用函数退出状态

[英]In bash script, how to use function exit status in while loop condition

Below is my shell script.下面是我的shell脚本。 How to compare the exit status of function in while loop condition block ?如何比较while循环条件块中函数的退出状态? Whatever I return from check1 function my code enters into while loop无论我从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

Remove the test command - also known as [ .删除test命令 - 也称为[ So:所以:

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 command after a conditional statement.从 Bourne 和 POSIX shell 派生的 shell 在条件语句之后执行命令 One way to look at it is that while and if test for success or failure, rather than true or false (although true is considered successful).一种看待它的方法是whileif测试成功或失败,而不是 true 或 false(尽管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

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
    # ...

For completeness, another way is using the function exit code inline of the while为了完整起见,另一种方法是使用while内联函数退出代码

 while check1  ; [ $? -eq 0 ] ; do

from here这里

You can also use parameters if you change your method to the "echo" style return value .如果将方法更改为“echo”样式返回值,也可以使用参数。

 while [ $(check1 my_param) < 33] ; do ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM