In a bash script, how to call a function during a loop
Below is my shell script. How do I compare the exit state of a function during a loop cycle loop? Whatever I return from the function check1
, my code goes into a 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
source to share
Remove the command test
, 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 Bourne and POSIX shells execute the command after the conditional statement. One way to look at it is that while
and if
check the success or failure, not true or false (although true
considered successful).
By the way, if you must check explicitly $?
(which is not so often required), then (in Bash) the construct is (( ))
usually easier to read, as in:
if (( $? == 0 ))
then
echo 'worked'
fi
source to share
The value returned by executing a function (or command) is stored in $?, One solution:
check1
while [ $? -eq 1 ]
do
# ...
check1
done
A nicer and simpler solution might 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 a value:
# the body of the next if is never executed
if ! true
then
# ...
source to share