Bash

循環直到 grep 在文件中找不到文本

  • October 30, 2020

我有一個名為file.txt. 文件內容如下

sunday
monday
tuesday

我寫了下面的腳本,如果grep找不到提到的模式,它就會循環

until cat file.txt | grep -E "fdgfg" -C 9999; do sleep 1 | echo "working..."; done

但我的要求是上面的腳本應該循環,直到grep模式中提到的文本消失在 file.txt

我嘗試將L標誌與 grep 一起使用。但它沒有用。

until cat file.txt | grep -EL "sunday" -C 9999; do sleep 1 | echo "working..."; done

grep手冊頁:

EXIT STATUS
  Normally the exit status is 0 if a line is selected, 1 if no lines were
  selected, and 2 if an error occurred.  However, if the -q or --quiet or
  --silent is used and a line is selected, the exit status is 0  even  if
  an error occurred.

因此,如果存在一行,則退出狀態為 0。由於 bash 0 為真(因為程序的標準“成功”退出狀態為 0),您實際上應該具有以下內容:

#!/bin/bash

while grep "sunday" file.txt > /dev/null;
do
   sleep 1
   echo "working..."
done

你到底為什麼要sleep 1echo?雖然有效,但意義不大。如果你想讓它們內聯,你可以寫sleep 1; echo "working...",如果你想echo在延遲之前執行,你可以在sleep呼叫之前擁有它,比如echo "working..."; sleep 1.

引用自:https://unix.stackexchange.com/questions/323577