在Shell脚本中添加Counter [英] Adding Counter in shell script

查看:132
本文介绍了在Shell脚本中添加Counter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的shell脚本中有以下代码,如果找不到任何文件,它将保持休眠状态.它睡眠了半个小时,但目前我没有任何计数器,例如只执行以下代码20次,然后如果文件仍然不存在,则退出程序(意味着20次检查后不执行任何操作并退出完整脚本).

I have below code in my shell script which will keep on sleeping if it doesn't finds any file. And it sleeps for half an hour but currently I don't have any counter like only execute the below code 20 times and then exit the program if the files are still are not there (means don't do anything after 20 checks and exit the full script).

解决此问题的最佳方法是什么?因此,通过查看它已尝试20次的电子邮件,我也知道了.

What's the best way to do this problem? So that I am also aware by looking at the emails that it has tried 20 times.

希望我很清楚.

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

推荐答案

以下是实现计数器的方法:

Here's how you might implement a counter:

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]];然后-检查 $ counter 是否不大于 20 .如果是这样,它将输出适当的消息并退出您的while循环.
  • counter=$((counter+1)) - this is how you can increment a counter. The $ for counter is optional inside the double parentheses in this case.
  • elif [[ "$counter" -gt 20 ]]; then - this checks whether $counter is not greater than 20. If so, it outputs the appropriate message and breaks out of your while loop.

这篇关于在Shell脚本中添加Counter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆