0

编写了一个脚本,该脚本接受用户输入的时间,并且应该在当前时间等于用户输入的时间时终止程序。

它分解为:

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。

有小费吗?

4

1 回答 1

1

while循环有几个问题:

  • 主要问题是NOW变量没有在循环内更新
  • 检查只需要(最多)每秒发生一次;所以sleep 1循环内部会阻止它占用 CPU 资源(添加从 'd 消息淹没标准输出)echo

也许一个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
于 2021-05-07T16:59:55.053 回答