Reputation: 1
Im modifying an existing bash script and having some trouble getting the while loop behaving correctly. This is the original code
while ! /usr/bin/executable1
do
# executable1 returned an error. So sleep for some time try again
sleep 2
done
I would like to change this to the following
while ! /usr/bin/executable1 && ! $(myfunc)
do
# executable1 and myfunc both were unsuccessful. So sleep for some time
sleep 2
done
executable1 returns 0 on success and 1 on failure. I understand that "true" in bash evaluates to 0 so thats why the original script would keep looping till executable returned success
Accordingly myfunc is coded like this
myfunc ()
{
# Check if file exists. If exits, return 0, If not, return 1
if [ -e someFile ]; then
return 0
fi
return 1
}
I notice that the my new while loop does not seem to call executable1. It always calls myfunc() and then exits out of the loop immediately. What am I doing wrong?
I tried various ways of coding the while loop (with (( )), [ ], [[ ]] etc), but nothing seems to fix it
Upvotes: 0
Views: 155
Reputation: 532368
You don't need $(...)
to call a function, just to capture its standard output. You simply want
while ! /usr/bin/executable1 && ! myfunc
do
sleep 2
done
Note that myfunc
can also be more simply written
myfunc () {
[ -e someFile ]
}
or even (in bash
)
myfunc () [[ -e someFile ]]
Either way, it's almost not worth defining myfunc
separately; just use
while ! /usr/bin/executable1 && ! [[ -e someFile ]]
do
sleep 2
done
It might also be simpler to use an until
loop:
until /usr/bin/executable1 || [[ -e someFile ]]; do
sleep 2
done
Upvotes: 1