我的 shell 脚本中有以下代码,如果找不到任何文件,它将继续休眠。它睡了半个小时,但目前我没有任何计数器,比如只执行下面的代码 20 次,然后如果文件仍然不存在则退出程序(意味着在 20 次检查后不做任何事情并退出完整脚本)。
解决这个问题的最佳方法是什么?所以我通过查看电子邮件也知道它已经尝试了 20 次。
希望我已经足够清楚了。
while true; do
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
break
else
echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now" -r admin@host.com admin@host.com
sleep 1800
fi
done
最佳答案
以下是您可以如何实现计数器:
counter=0
while true; do
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
elif [[ "$counter" -gt 20 ]]; then
echo "Counter: $counter times reached; Exiting loop!"
exit 1
else
counter=$((counter+1))
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
done
一些解释:
counter=$((counter+1))
- 这是递增计数器的方法。在这种情况下,counter
的$
在双括号内是可选的。elif [[ "$counter"-gt 20 ]]; then
- 检查$counter
是否不大于20
。如果是,它会输出适当的消息并跳出您的 while 循环。
关于bash - 在 shell 脚本中添加计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13638670/