【问题标题】:Shell read from files with tailShell 从带有尾部的文件中读取
【发布时间】:2020-03-10 02:43:07
【问题描述】:

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

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

但是,它返回错误syntax error near unexpected token('`

我尝试关注How to use while read line with tail -n,但仍然看不到错误。

tail 命令正常工作。

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

【问题讨论】:

  • posix shell /bin/sh 不支持进程替换。它是 bash (和其他)特有的功能。你在/bin/bash 运行这个吗?

标签: bash shell sh process-substitution


【解决方案1】:

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

【讨论】:

  • 是的...你是对的....直到您提及...才意识到这一点...谢谢您的帮助...
【解决方案2】:

您的解释器必须是#!/bin/bash 而不是#!/bin/sh 和/或您必须使用bash scriptname 而不是sh scriptname 运行脚本。

为什么?

POSIX shell 不提供进程替换。进程替换(例如&lt; &lt;(...))是一种bashism,在POSIX shell 中不可用。所以报错:

syntax error near unexpected token('

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2015-07-29
    • 2018-08-22
    • 2011-08-07
    • 2014-09-27
    相关资源
    最近更新 更多