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
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
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
# ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With