问题描述
编写了一个脚本,接受用户输入的时间,并且应该在当前时间等于用户输入的时间时终止程序。
细分为:
read -p "Enter when your class ends in the format 00:00 " endclass
echo "We will close your meeting at $endclass"
Now=$(date +"%H:%M")
while True
do
echo "Waiting for class to end..."
if [ $Now = $endclass ]
then
pkill Chrome
fi
done
将 if 语句放在 while 循环中继续执行脚本,直到当前时间达到所需时间。
我可以在没有任何错误的情况下运行脚本,但它根本不会杀死 Chrome。
有什么建议吗?
解决方法
while 循环有几个问题:
- 主要问题是
NOW
变量在循环内没有更新 - 检查只需要(最多)每秒进行一次;所以循环内的
sleep 1
会阻止它占用 CPU 资源(添加echo
的消息不会使 stdout 泛滥)。
也许 while 循环的替代方法是为精确的秒数添加睡眠,例如:
echo "Waiting for class to end..."
# Determine how many seconds to the endclass time:
# 1. Have the date command finish the seconds-based arithmetic expression
# 2. Then,sleep for the bash-shell evaluated number of seconds from the expression
endclass_h="${endclass%%:*}"
endclass_m="${endclass##*:}"
sleep $(( endclass_h*3600 + endclass_m*60 - $(date +"%H*3600 - (10#%M*60 + 10#%S)") ))
pkill Chrome