在子进程中嵌套while循环

时间:2016-08-22 12:39:56

标签: bash shell while-loop nested-loops

我的bash脚本遇到了关于打破嵌套的while循环的问题,该循环从带有tail的日志文件中读取一行。

我需要什么:读取日志文件的嵌套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调用一个或另一个循环。

1 个答案:

答案 0 :(得分:-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
}