为什么重定向到 while 循环不打印消息?

Sea*_*ene 1 command-line tail

这是用于跟踪文件中的更改并将内容输出到终端的 shell 代码:

while read LINE
do
  echo $LINE
done < `tail -f /var/log/messages`
Run Code Online (Sandbox Code Playgroud)

它不起作用,为什么?

cha*_*aos 5

不需要while循环。你尝试做两次同样的事情。此外,该文件/var/log/messages不再存在于 ubuntu 中。

只需使用:

tail -f /var/log/syslog
Run Code Online (Sandbox Code Playgroud)

跟踪添加在文本文件末尾的新内容。如果将新内容写入其末尾,/var/log/syslog则会将其打印到您的终端。

编辑:为什么问题中的命令不起作用:

首先,当然/var/log/messages不存在。但如果它存在,反引号之间的命令将被执行并替换为其输出(减去尾随换行符)。所以输出tail -f ...将作为输入重定向的文件名<。您可能想要的内容如下(<(...)重定向):

while read LINE; do
  echo $LINE
done < <(tail -f /var/log/messages)
Run Code Online (Sandbox Code Playgroud)

<(...)重定向创建命名的管道,其中一端的命令tail -f写入。在另一端,while循环逐行读取内容。命名管道的行为可能与常规文件相同。它只是两个命令之间的连接件。顺便说一句,|完全相同,但那些管道没有命名,它们是默认通道:0 -> stdin,1 -> stdout 和 2 -> stderr。

bash联机帮助页:

 Process substitution is supported on systems that support named pipes (FIFOs) or the 
 /dev/fd method of naming open files. It takes the form of <(list) or >(list).  
Run Code Online (Sandbox Code Playgroud)