Adding Counter in shell script

前端 未结 2 1120
花落未央
花落未央 2021-01-30 12:50

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

2条回答
  •  广开言路
    2021-01-30 12:59

    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
    

    Some Explanations:

    • 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.

提交回复
热议问题