2016-08-22 114 views
-1

我遇到了一个问题,我的bash脚本打破了一个嵌套的while循环从尾部的日志文件中读取一行。嵌套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的函数尝试过它。

+1

相关? [在while循环中修改变量不记住](http://stackoverflow.com/q/16854280/1983854) – fedorqui

+0

我不这么认为。他不必逃避while循环。我只需要在while循环中找到一行,否则什么都没有。 –

+1

那么,你的代码有什么问题?它是否因错误而失败?它不像你期望的那样运行吗?不要只是粘贴你的代码,并期望我们找出问题和解决方案。 – larsks

回答

-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 
} 
+0

不幸没有成功。第一条if语句没有执行。 –

+0

我编辑了代码。你可以再试一次,请 –

+0

你可能已经改变了在if语句中的右边那个变量?我看到它已经哈哈!不管怎样,谢谢。 –