如何在 bash/linux 脚本中执行相同的循环 1 小时?
我想以随机间隔打开和关闭一些网页一小时。
到目前为止,我已经写了内部结构
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
,所以我缺少 while 条件。
我想要这样的东西:
TIMER = 0h 0m 0s
while( TIMER < 1 h)
....
done
这可能吗?
附言。随机数的命令是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一定。尝试:
date +%s
显示自 1970 年以来的当前时间(以秒为单位)。循环计算一小时前的当前日期并检查它是否超过开始时间。Surely. Try:
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.实现此目的的一种方法是使用信号和陷阱。这是一个简单的例子:
评论是不言自明的(我希望)。第一部分启动一个后台进程,该进程仅休眠一段时间(本例中为 10 秒),然后当它醒来时,向原始进程发送 SIGUSR1。
shell 脚本捕获此情况(使用
trap
),然后向其自己的 PID 发出kill
,停止进程。其余部分只是一个无限循环——它是杀死脚本并终止循环的
陷阱
。从技术上讲,您不需要上面示例中的陷阱:后台进程可以直接发出
kill $me
,但为了完整起见,我将其包含在内,因为您可以将其用作钩子来执行其他操作(例如,如果您不想死,但设置一个标志并让循环自然终止,或者在终止之前需要进行一些清理工作)。One way you can do this is with signals and traps. Here's a simple example:
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 akill
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).这是我的解决方案:
This is my solution :
我的解决方案基于 来自 thiton 的解决方案:
也可以很好地内嵌:
My solution is based on the one from thiton:
Also works fine inline: