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?
if [ $# -ne 1 ]; then # only 1 command line arg allowed
echo "Incorrect arguments"
elif ! [[ $1 =~ ^[0-9]+$ ]]; then # arg must be digit
echo "Argument must be a positive number"
OUTPUT=$(snmpwalk -v2c -c community server oib)
#export -f ask
#watch -n5 ask
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).