问题
I want to open and close some web pages with random intervals for an hour.
So far i have written the innards
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'm am missing the while condition.
I want something like:
TIMER = 0h 0m 0s
while( TIMER < 1 h)
....
done
Is this possible?
PS. what's the command to random number?
回答1:
Surely. 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 computes the current date of an hour ago and checks if it exceeds the start time.
回答2:
One way you can do this is with signals and traps. Here's 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
The comments are self-explanetory (I hope). The first part kicks off a background process that just sleeps for a period of time (10 seconds in this example), and then when it wakes up sends SIGUSR1 to the originating process.
The shellscript catches this (with trap
) and just issues a kill
to its own PID, stopping the process.
The rest of it is just an infinite loop -- it's the trap
that kills the script and terminates the loop.
Technically you don't need the trap in the example above: the background process could just issue kill $me
directly, but I've included it for completeness as you can use it as a hook to do other things (e.g., if you don't want to die but set a flag and have the loop terminate naturally, or you have some clean-up to do before terminating).
回答3:
This is my solution :
#!/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
来源:https://stackoverflow.com/questions/8168428/how-to-execute-the-same-loop-for-1-hour-in-bash-linux-scripting