我不确定之前是否曾经问过这个问题,但是如果我有一个运行无限循环的脚本:
#!/bin/bash
while :
do
echo "Press [CTRL+C] to stop.."
sleep 1
done
我只想运行它10秒,但我不想让它立即停止,例如,在psudo代码中,我想要这样的东西:
while true:
if 10 seconds elapsed:
do something
then kill
else
keep going #this takes an arbitrary amount of time
我尝试了gtimeout,它确实在一段时间后终止了进程,但我的问题是内部循环不知道已经过了多少时间。有什么东西可以添加到脚本本身来实现吗?
谢谢!
答案 0 :(得分:1)
NUM_SECS_TO_RUN=605 # Time you want to run for in seconds, 1 day would be 84600
TIME_NOW=$( date +"%H:%M:%S" )
END_TIME=$( date -d "${TIME_NOW} today + ${NUM_SECS_TO_RUN} seconds" +"%y%m%d%H%M%S" )
echo "Starting" $(date)
while [ $( date +"%y%m%d%H%M%S" ) -lt ${END_TIME} ]
do
# whatever it is that you want to do repeatedly until the period expires
do_something
done
echo "Expired" $(date)
do_something_at_end # whatever it is you want to do right at the end
echo "FInished" $(date)
有几件事:
答案 1 :(得分:0)
for t in 0 1 2 3 4 5 6 7 8 9 ; do
if [ $t -eq 9 ] ; then
#do something
kill
break
fi
echo "Press [CTRL+C] to stop.."
sleep 1
done
# keep going
运行24小时,每秒检查一次(注意我将提示退出循环,所以它不必回复86400次):
t=0
echo "Press [CTRL+C] to stop.."
while true ; do
if [ $t -eq 86400 ] ; then
#do something
kill
break
fi
sleep 1
t=$(( t + 1 ))
done
# keep going