John Setter John Setter - 26 days ago 9
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:

#!/bin/bash

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
fi

ask()
{
OUTPUT=$(snmpwalk -v2c -c community server oib)
CLEANOUTPUT="${OUTPUT:32}%"
echo $CLEANOUTPUT
}

#export -f ask
#watch -n5 ask

Answer

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

#!/bin/bash

while (( SECONDS <= 20 ))
do
  echo "Running something"
  sleep 5 || break
done
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).