Mihir Mihir - 6 months ago 64
Bash Question

Time condition loop in shell

I have just started learning shell script recently, so I don't know much about it.

I am trying to find example of time based while loop but not having any luck.

I want to run a loop for specific amount of time, let's say 1 hour. So loop runs for an hour and then ends automatically.

Edit: This loop will run continiously without any sleep, so the loop condition should be based on loop's start time and current time, not on sleep.


The best way to do this is using the $SECONDS variable, which has a count of the time that the script (or shell) has been running for. The below sample shows how to run a while loop for 3 seconds.

#! /bin/bash

while [ $SECONDS -lt $end ]; do
    # Do what you want.