【问题标题】:Nested while loops in subprocess子进程中的嵌套while循环
【发布时间】:2016-08-22 12:39:55
【问题描述】:

我的 bash 脚本有一个问题,即中断一个嵌套的 while 循环,该循环从带有尾部的日志文件中读取一行。

我需要什么:读取日志文件的嵌套 while 循环应该找到一些正则表达式。如果这是真的,将其保存到一个变量中并打破循环。在循环之外还有另一个 while 循环,用于检查是否该将一些数据发送到 Confluence 页面。如果不是时候什么都不做,直到在 while 循环中找到符合正则表达式的行。

我做了一个 MVCE:

#!/bin/bash    

counterSearch=0    

tail -n0 -f $logfile | {
    while true; do
        currentMinute=$(date +%S)    

        # Checks if $currentSecond is set to 59. If true do something.
        # Else go back to while loop.
        if [[ $currentSecond -eq 59 ]]; then
           echo "Hello. This is 59 seconds outside while read line loop"
        fi

        # This while loop should always check if in the $logfile a specific line if found.
        # If true save it and go back to the outside while loop. When a new line is found
        # execute it again.
        while read line ; do
            if echo "$line" | grep -e "/rest/api/2/search.*PASSED" 1>/dev/null 2>&1 ; then
               echo "$date - Search and passed API action" >> $log
               counterSearch=$((counterSearch+1))
            fi
        done
    done
}    

问题在于内部的 while 循环一直在运行。如果没有突破到外部 while 循环。我已经尝试过使用函数和带有 if/else 调用一个或另一个循环的函数。

【问题讨论】:

  • 我不这么认为。他不必逃避 while 循环。只有在找到一行时才需要 while 循环,否则什么也没有。
  • 那么,您的代码有什么问题?它是否因错误而失败?它没有像您期望的那样运行吗?不要只是粘贴您的代码并期望我们找出问题解决方案。
  • 问题是一直在while循环中运行。如果没有突破到外部 while 循环。我已经尝试过使用函数和带有 if else 调用一个或另一个循环的函数。
  • 您需要取消嵌套循环并在后台运行其中一个。当 currentSecond 检查想要退出时,它应该终止读取行循环。 (我会写一个正确的答案,但我必须离开。)

标签: bash shell while-loop nested-loops


【解决方案1】:

while循环在子shell中执行

试试这个代码:

#!/bin/bash    

export counterSearch=0    

tail -n0 -f $logfile | {
    while true; do
        currentMinute=$(date +%M)  
        currentSecond=$(date +%S)   

        # Checks if $currentSecond is set to 59. If true do something.
        # Else go back to while loop.
        if [[ $currentSecond -eq 59 ]]; then
           echo "Hello. This is 59 seconds outside while read line loop"
        fi

        # This while loop should always check if in the $logfile a specific line if found.
        # If true save it and go back to the outside while loop. When a new line is found
        # execute it again.
        while read line ; do
            if echo "$line" | grep -e "/rest/api/2/search.*PASSED" 1>/dev/null 2>&1 ; then
               echo "$date - Search and passed API action" >> $log
               export counterSearch=$((counterSearch+1))
            fi
        done
    done
}  

【讨论】:

  • 很遗憾没有成功。第一个 if 语句没有被执行。
  • 您可能在 if 语句中将变量更改为正确的变量?我已经看过了哈哈!无论如何,谢谢。
  • 是的,我添加了正确的可验证名称和导出语句。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-26
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多