John Setter John Setter - 1 year ago 99
Bash Question

Shell Script to run command every 5secs for x number of secs

I'm learning bash scripting and I want to call a function every 5 seconds for x number of seconds. The x is determined by the command line argument when the script was run. I've tried watch but it seems to go on forever, I don't seem to have an ability to return after x seconds. There might be a sleep way but it seems clumsy and I have to deal with local drift. Is there an elegant solution?

My code:


if [ $# -ne 1 ]; then # only 1 command line arg allowed
echo "Incorrect arguments"
exit 1
elif ! [[ $1 =~ ^[0-9]+$ ]]; then # arg must be digit
echo "Argument must be a positive number"
exit 1

OUTPUT=$(snmpwalk -v2c -c community server oib)

#export -f ask
#watch -n5 ask

Answer Source

The SECONDS variable counts the number of seconds since bash was started:


while (( SECONDS <= 20 ))
  echo "Running something"
  sleep 5 || break
echo "Done"

This simplistic method will sleep 5 after the last run even when you know it'll go over 20 seconds, and it does not try to account for the run time of the command (if the command runs for 2 seconds, it'll end up starting up once every 7 seconds).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download