在shell脚本中添加计数器

ars*_*nal 52 bash shell

我的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
Run Code Online (Sandbox Code Playgroud)

sam*_*hen 90

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

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
Run Code Online (Sandbox Code Playgroud)

一些解释:

  • counter=$((counter+1)) - 这是你增加一个计数器的方法.该$用于counter在这种情况下,双括号内可选的.
  • elif [[ "$counter" -gt 20 ]]; then- 这检查是否$counter不大于20.如果是这样,它会输出相应的消息并突破你的while循环.


koo*_*ola 15

试试这个:

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
       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 admin@host.com admin@host.com
       sleep 1800
  fi
done
Run Code Online (Sandbox Code Playgroud)

说明

  • break - 如果文件存在,它将中断并允许脚本处理文件.
  • [[ "$counter" -gt 20 ]] - 如果计数器变量大于20,脚本将退出.
  • let counter++ - 每次通过时将计数器递增1.

  • 我喜欢 `let counter++` 的语法,而不是用一堆美元的旧语法 :) (3认同)