2012-11-30 70 views
32

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

解决此问题的最佳方法是什么?所以我通过查看已经尝试了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 [email protected] [email protected] 
     break 
    else 
     echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now" -r [email protected] [email protected] 
     sleep 1800 
    fi 
done 

回答

54

这里是你将如何实现一个计数器:

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 [email protected] [email protected] 
     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 [email protected] [email protected] 
     sleep 1800 
    fi 
done 

一些解释:

  • counter=$((counter+1)) - 这是你可以增加一个计数器。在这种情况下,$对于counter在双括号内是可选的。
  • elif [[ "$counter" -gt 20 ]]; then - 这检查$counter是否不大于20。如果是这样,它会输出适当的消息并跳出while循环。
+0

谢谢桑普森的建议。而不是在'elif'中做'break'有什么办法可以退出脚本?为什么我问这是因为'完成'行之后,我有更多的代码要执行,所以只有当文件存在时才执行,但在添加此计数器检查后,我不想在执行完这些代码之后如果文件仍然不存在,则检查20次。 – ferhan

+0

@TechGeeky要退出脚本本身,请执行'exit 0'(如果终止如预期的那样)或'exit 1'(如果终止并且您想指示发生了某种错误) –

+0

我试过上面的代码, 'counter = $((counter + 1))'这一行为'$'意外。为什么这样?我正在使用'sh -x test1.sh'运行上面的脚本。 – ferhan

4

试试这个:

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 [email protected] [email protected] 
     break 
    elif [[ "$counter" -gt 20 ]]; then 
     echo "Counter limit reached, exit script." 
     exit 1 
    else 
     let counter++ 
     echo "Sleeping for another half an hour" | mailx -s "Time to Sleep Now" -r [email protected] [email protected] 
     sleep 1800 
    fi 
done 

说明

  • break - 如果文件存在,这将打破,并允许脚本处理的文件。
  • [[ "$counter" -gt 20 ]] - 如果计数器变量大于20,脚本将退出。
  • let counter++ - 在每次通过时将计数器增加1。