【问题标题】:Bash Shell Do While Loop Infinite loop?Bash Shell Do While Loop 无限循环?
【发布时间】:2011-12-16 12:56:40
【问题描述】:

基本上这是我的代码:

bay=$(prog -some flags)
while [ $bay = "Another instance of this program is running, please exit it first" ]
do
echo "Awaiting Access to program"
do
.....

我有一个程序,由于它与我的硬件交互的方式,它一次只允许一个实例运行,当另一个实例运行时,它会弹出以下消息“该程序的另一个实例正在运行,请退出首先”。

我需要能够运行多个使用同一程序的脚本,所以我决定使用上面的代码。我的问题是,当我运行我的两个脚本时,一个将获得对程序的访问权并按需要运行,但另一个会注意到错误,然后卡在一个无限循环中,回显“等待访问程序”。

错过了什么?该语句是在执行 CLI 命令还是只是返回其原始执行?还是我的问题出在哪里?

【问题讨论】:

    标签: linux bash shell while-loop do-while


    【解决方案1】:

    您没有在某处的循环内更新您的bay 变量。它被设置一次并保持不变。每次都需要重新计算。

    要么在循环内设置bay,要么在while的条件下设置。

    while [ `prog -some flags` = "Another instance of this program is running, please exit it first" ]
    

    编辑:

    根据您的评论,您希望以后能够引用此输出。你可以回到你所拥有的,但是在你的阻塞循环中,将你的 bay=$(prog -some flags) 命令放在循环中。它会一直留着供您以后使用。

    bay=$(prog -some flags)
    while [ $bay = "Another instance of this program is running, please exit it first" ]
    do
    echo "Awaiting Access to program"
    bay=$(prog -some flags)
    done
    .....
    

    【讨论】:

    • 是否有任何方法可以在随后的 If Else 语句中调用该变量?还是我应该开始一个新的变量?
    • 我更新了我的回复,为您的新要求提供建议。
    【解决方案2】:

    更多DRY,而不是锤击编,我会等待用户先做某事:

    while true
    do
      bay=$(prog -some flags)
      case "$bay" in
        "Another instance of this program is running, please exit it first")
          read -p "Awaiting Access to program. Close it and hit enter: " x ;;
        *) break ;;
      esac
    done
    echo "Results: $bay"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 2015-12-20
      • 2015-11-01
      相关资源
      最近更新 更多