【问题标题】:If Statement to Kill Program at User Set Time - BashIf 语句在用户设置的时间杀死程序 - Bash
【发布时间】:2021-07-29 21:18:15
【问题描述】:

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

分解为:

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。

有什么建议吗?

【问题讨论】:

  • @Cyrus 更新,我尝试将 True 更改为 true -- 不走运,仍然无法杀死 Chrome

标签: bash if-statement scripting pkill


【解决方案1】:

while 循环有几个问题:

  • 主要问题是NOW 变量没有在循环内更新
  • 检查只需要(最多)每秒进行一次;所以循环内的sleep 1 会阻止它占用CPU 资源(添加echo'd 消息泛滥​​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

【讨论】:

    猜你喜欢
    • 2017-05-13
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 2015-07-27
    相关资源
    最近更新 更多