【问题标题】:How to wait for the value of a variable to be set true until a certain time interval如何等待变量的值设置为真,直到某个时间间隔
【发布时间】:2018-10-16 16:46:19
【问题描述】:

场景:
我有一个在嵌入式 linux 上运行的 shell 脚本。该脚本启动一个需要打开变量状态的应用程序。

代码:
所以我就这样做了

#!/bin/sh

start_my_app=false

wait_for_something=true
while $wait_for_something; do

    wait_for_something=$(cat /some/path/file)

    if [ "$wait_for_something" = "false" ]
    then
        echo Waiting...
    elif [ "$wait_for_something" = "true" ]
    then
        echo The wait has ended
        wait_for_something=false
        start_my_app=true
    else

    fi

done

if [ "$start_my_app" = "true" ]
then
    /usr/bin/MyApp
fi

#End of the script

/some/path/file 有一个值false,并在几秒钟内被不同组件中的另一个脚本转换为true。然后随着逻辑的发展,我脚本中的wait_for_something 变为true 并启动/usr/bin/MyApp

问题和问题:
但我想以更好的方式做到这一点。
我不想在等待一段时间后无限期地等待/some/path/file 中的内容值true

我想等待 /some/path/file 中的内容值设置为 true 仅 5 秒。如果/some/path/file 在 5 秒内不包含true,我想将start_my_app 设置为false。

如何在 linux 上的 shell 脚本中实现此功能?

PS:
我的整个脚本由另一个脚本在后台运行

【问题讨论】:

标签: linux bash shell sh


【解决方案1】:

使用SECONDS 变量作为计时器。

SECONDS=0
while (( SECONDS < 5 )) && IFS= read -r value < /some/path/file; do
  if [[ $value = true ]]; then
    exec /usr/bin/MyApp
  fi
done

如果您从未从文件中读取过true,您的脚本将在 5 秒后退出。否则,脚本会用MyApp 替换当前shell,从而有效地退出while 循环。

【讨论】:

  • 好消息是SECONDS 也可以在 POSIX shell 中使用,而不仅仅是bash
  • @ob-ivan SECONDS 不是 POSIX 定义的。比如dash中的一个普通变量。
  • 我的错,我没有正确测试它。我的循环在达到超时之前就退出了,所以我只是假设它有效。增加一个普通变量是一种方法。
猜你喜欢
  • 2020-06-21
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-09
  • 2016-08-21
相关资源
最近更新 更多