Dam*_*men 6 shell grep bash shell-script
我有一个名为file.txt
. 文件内容如下
sunday
monday
tuesday
Run Code Online (Sandbox Code Playgroud)
我写了下面的脚本,如果grep
找不到提到的模式,它就会循环正常
until cat file.txt | grep -E "fdgfg" -C 9999; do sleep 1 | echo "working..."; done
Run Code Online (Sandbox Code Playgroud)
但是我的要求是上面的脚本应该循环直到grep
模式中提到的文本在 file.txt
我尝试将L
标志与 grep一起使用。但它没有用。
until cat file.txt | grep -EL "sunday" -C 9999; do sleep 1 | echo "working..."; done
Run Code Online (Sandbox Code Playgroud)
Ian*_*anC 17
从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.
Run Code Online (Sandbox Code Playgroud)
因此,如果存在一行,则退出状态为 0。由于在 bash 上 0 为真(因为程序的标准“成功”退出状态为 0),您实际上应该具有以下内容:
#!/bin/bash
while grep "sunday" file.txt > /dev/null;
do
sleep 1
echo "working..."
done
Run Code Online (Sandbox Code Playgroud)
为什么你到底是管道sleep 1
来echo
?虽然有效,但意义不大。如果您希望它们内联,您可以直接编写sleep 1; echo "working..."
,如果您希望echo
在延迟之前运行,您可以在sleep
调用之前拥有它,例如echo "working..."; sleep 1
.