Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time condition loop in shell

Tags:

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.

like image 318
Mihir Avatar asked Jun 24 '12 09:06

Mihir


People also ask

How do you write a loop in shell script?

1) Syntax:Syntax of for loop using in and list of values is shown below. This for loop contains a number of variables in the list and will execute for each item in the list. For example, if there are 10 variables in the list, then loop will execute ten times and value will be stored in varname.

How do you display time in shell?

Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...

What is $i in shell script?

${-#*i} means shell flags minus first match of *i . If these two are not equal, then the shell is considered interactive (flag i is present).


1 Answers

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 end=$((SECONDS+3))  while [ $SECONDS -lt $end ]; do     # Do what you want.     : done 
like image 169
bsravanin Avatar answered Oct 01 '22 18:10

bsravanin