Shell 使用尾部读取文件

Shell read from files with tail

我目前正在尝试使用 shell 读取文件。但是,我遇到了一个语法问题。我的代码如下:

while read -r line;do
    echo $line
done < <(tail -n +2 /pathToTheFile | cut -f5,6,7,8 | sort | uniq )

然而,它 returns 我的错误 syntax error near unexpected token('`

我尝试了以下 但仍然看不到错误。

tail 命令正常工作。

如有任何帮助,我们将不胜感激。

您的解释器必须 #!/bin/bash 而不是 #!/bin/sh and/or 您必须 运行 脚本 bash scriptname 而不是 sh scriptname

为什么?

POSIX shell 不提供 过程替代 。流程替换(例如 < <(...))是一种 bash 主义,在 POSIX shell 中不可用。所以错误:

syntax error near unexpected token('

告诉您,一旦脚本到达您的 done 语句并尝试查找被重定向到循环的文件,它会发现 '(' 并阻塞。 (这也告诉我们您正在使用 POSIX shell 而不是 bash 调用您的脚本——现在您知道为什么了)

process substitution 不受 posix shell /bin/sh 支持。它是 bash(以及其他非 posix shell 的特定功能)。你是 运行 /bin/bash 中的这个吗?

无论如何,这里不需要进程替换,您可以简单地使用管道,如下所示:

tail -n +2 /pathToTheFile | cut -f5,6,7,8 | sort -u | while read -r line ; do
    echo "${line}"
done