Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

sh

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

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

    while [ check1 ]
    do
            echo $?
            check1
            if [ $? -eq 0 ]; then
                    echo "Called"
            else
                    echo "DD"
            fi
            sleep 5
    done
like image 630
Krishna M Avatar asked Dec 28 '14 08:12

Krishna M


2 Answers

Remove the test command - also known as [. 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. 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).

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:

if (( $? == 0 ))
then
    echo 'worked'
fi
like image 174
cdarke Avatar answered Sep 26 '22 11:09

cdarke


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
    # ...
like image 37
Fernando Avatar answered Sep 25 '22 11:09

Fernando