How to execute the same loop for 1 hour in bash / linux scripts?

I want to open and close some web pages at random intervals for an hour.

So far I have written insides

FILE=webpages TIMES=0 while test $TIMES -lt 10 do #Picks random line(Website) from FILE TEMPWEB=`shuf -n 1 $FILE` echo "Opening" $TEMPWEB #Opens TEMPWEB xdg-open $TEMPWEB sleep 10 #Kills firefox ps -e | grep firefox | sed 's/\(.[0-9]*\).*/\1/' | xargs kill TIMES=$(($TIMES+1)) done 

So, I am missing the while condition.
I need something like:

 TIMER = 0h 0m 0s while( TIMER < 1 h) .... done 

Is it possible?

PS. what is the random number command?

+4
source share
3 answers

Sure. Try:

 #!/bin/bash START=`date +%s` while [ $(( $(date +%s) - 3600 )) -lt $START ]; do .... done 

date +%s shows the current time in seconds since 1970. The loop calculates the current date an hour ago and checks if it exceeds the start time.

+13
source

One way to do this is through signals and traps. Here is a simple example:

 #!/bin/bash me=$$ # Start a background process to signal us when the time has passed ( sleep 10 kill -USR1 $me ) & # When we recieve SIGUSR1, commit suicide trap "kill $me" SIGUSR1 # Do stuff until we commit suicide while [ 1 -eq 1 ] do echo 'Hello!' sleep 1 done 

Comments are self-sufficient (hopefully). The first part starts the background process, which simply sleeps for a certain period of time (10 seconds in this example), and then, when it wakes up, sends SIGUSR1 to the original process.

The shell call catches this (using trap ) and simply issues kill to its own PID, stopping the process.

The rest is just an endless loop - it's a trap that kills the script and terminates the loop.

Technically, you don’t need a trap in the above example: the background process can simply issue kill $me directly, but I turned it on for completeness, since you can use it as a hook to perform other actions (for example, if you do not want to die, but set the flag and complete the loop naturally, or do you have some sort of cleanup to complete).

+9
source

This is my decision:

 #!/bin/bash # function to display a number in a range randrange() { echo $(( ( RANDOM % ($2 - $1 +1 ) ) + $1 )); } # sleep 1 hour and keep backgrounded PID in a variable sleep 3600 & _suicide_pid=$! # while the process is UP while kill &>/dev/null -0 $_suicide_pid; do # ----->8--- do what you want here <---8<----- sleep $(randrange 10 15) # random sleep in 10-15 range done 
+2
source

Source: https://habr.com/ru/post/1381708/


All Articles