11

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
rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Krishna M
  • 1,135
  • 2
  • 16
  • 32
  • I'm not sure why you're calling check1 twice? You should be able to assumed it was "Called" each time through that loop... – rogerdpack Jun 23 '21 at 16:28

3 Answers3

18

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
cdarke
  • 42,728
  • 8
  • 80
  • 84
10

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
    # ...
Fernando
  • 1,382
  • 8
  • 17
1

For completeness, another way is using the function exit code inline of the while

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

from here

You can also use parameters if you change your method to the "echo" style return value.

 while [ $(check1 my_param) < 33] ; do ...
rogerdpack
  • 62,887
  • 36
  • 269
  • 388