Tuesday, October 26, 2021

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

Issue

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

Solution

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


Answered By - cdarke