#!/usr/bin/env bash
counter=0
while [[ "$counter" -lt 20 ]]
do
if [[ $counter -gt 0 ]] ; then
echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now" -r admin@host.com admin@host.com
sleep 1800
fi
if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 ; then
echo "Files Present" | mailx -s "File Present" -r admin@host.com admin@host.com
exit 0
fi
: $((counter++))
done
echo "Counter: $counter times reached; Exiting loop!"
exit 1
Here's another take on this. I've added this bit of code to illustrate these points:
- The
while
can take your counter as the condition - this removes the need to check the variable value in the loop.
- Since the if branches cause the loop to end anyway ( via break or exit ) there is no need for the final
else
.
- I've provided a different syntax for increasing the counter. To be honest, I've never seen koola's version (
let counter++
) but I like it a lot (it's simpler to me).
- I'm not 100% sure that some of the while loops provide as answers actually loop 20 times. Rather, I think some of them loop 21 times.
- The solutions presented actually email the admin an extra time - there is no need to tell the admin that you are sleeping for a half an hour if you are going to be exiting anyway. I've added an additional if at the beginning of the while loop to avoid the extra email (and sleep).
Here's the output for a run that fails to find files 20 times:
Counter: 1 time(s); Sleeping for another half an hour
Counter: 2 time(s); Sleeping for another half an hour
...
Counter: 19 time(s); Sleeping for another half an hour
Counter: 20 times reached; Exiting loop!
The short of if is that we check for files 20 times, but only sleep 19 times.