Bash 使用tail跟踪日志并立即执行命令?似乎只有开一条新的生产线才能奏效

Bash 使用tail跟踪日志并立即执行命令?似乎只有开一条新的生产线才能奏效,bash,if-statement,grep,tail,less-unix,Bash,If Statement,Grep,Tail,Less Unix,我试图找出一个命令,使我能够实时读取日志文件,并在字符串匹配时执行命令?我使用的是日志键,当我键入一个单词时,它会立即触发一个命令。这个脚本可以工作,但只有当我按enter键(开始换行)时它才会执行,而且我在网上找到的任何东西似乎都需要按enter键才能工作。有没有办法绕过这个问题 #/bin/bash echo Waiting... string='test' tail /path/to/logfile -n0 -f | while read line; do if [[ $l

我试图找出一个命令,使我能够实时读取日志文件,并在字符串匹配时执行命令?我使用的是日志键,当我键入一个单词时,它会立即触发一个命令。这个脚本可以工作,但只有当我按enter键(开始换行)时它才会执行,而且我在网上找到的任何东西似乎都需要按enter键才能工作。有没有办法绕过这个问题

#/bin/bash
echo Waiting...
string='test'
tail /path/to/logfile -n0 -f | while read line; do
        if [[ $line =~ $string ]]; then
                echo "hello"
        fi
done

我使用了缓冲设置,但没有效果,所以我的结论是,
read
在换行结束之前等待换行。如果你改为
read-n1
read
将只读取一个字符,这也不是我们想要的,因为那样的话,
$line
将始终只是那一个字符

不幸的是,
grep
似乎具有相同的行为(即使缓冲选项已更改),即使是
grep-o

$ tail logfile -f -n0 | grep -o test &
[1] 25524
$ echo -n test >> logfile
$ echo -n test >> logfile
$ echo test >> logfile
test
test
test
认为一般的解决方案是使用我们自己的“环形缓冲区grep”搜索工具,将每个字符读取到环形缓冲区中

这是我的perl版本,希望能有所帮助。(另存为:
ringgrep.pl

用法:

$ chmod +x ringgrep.pl
$ tail logfile -n0 -f | ./ringgrep.pl "this is a test" &
[1] 25756
$ echo -n "test" >> logfile
$ echo -n "test" >> logfile
$ echo -n "test" >> logfile
$ echo -n "test" >> logfile
$ echo -n "this is a test" >> logfile
got test!
$ echo -n "this is a test" >> logfile
got test!
$ echo -n "this is a test" >> logfile
got test!
$ (echo -n t; echo -n h; echo -n i; echo -n s; echo -n ' '; echo -n i; echo -n s; echo -n ' '; echo -n a; echo -n ' '; echo -n t; echo -n e; echo -n s; echo -n t) >> logfile
got test!

当然,在bash中编写这篇文章是完全可能的,但无论如何,也许有更好的方法来实现这一点。
$ chmod +x ringgrep.pl
$ tail logfile -n0 -f | ./ringgrep.pl "this is a test" &
[1] 25756
$ echo -n "test" >> logfile
$ echo -n "test" >> logfile
$ echo -n "test" >> logfile
$ echo -n "test" >> logfile
$ echo -n "this is a test" >> logfile
got test!
$ echo -n "this is a test" >> logfile
got test!
$ echo -n "this is a test" >> logfile
got test!
$ (echo -n t; echo -n h; echo -n i; echo -n s; echo -n ' '; echo -n i; echo -n s; echo -n ' '; echo -n a; echo -n ' '; echo -n t; echo -n e; echo -n s; echo -n t) >> logfile
got test!