Getting error "cat: write error: Broken pipe" only when running bash script non-interactively

Getting error "cat: write error: Broken pipe" only when running bash script non-interactively

我写了一个 bash 脚本,我在其中定义了这样一个变量:

var=$(cat $file_path | head -n $var2 | tail -n 1 | cut -f1)

其中 $file_path 仅包含文件的路径,而 $var2 是一个整数,例如 1 或 2。因此,该变量被赋予行号 var2 的第一个字段的值文件。

当我从命令行 运行 时它工作得很好。但是,当 运行 运行包含此命令的脚本时,出现错误

cat: write error: Broken pipe

知道这是为什么吗?

不需要使用 cat,因为 head 接受文件名参数。

var=$(head -n $var2 $file_path | tail -n 1 | cut -f1)

实际上,没有必要使用任何这些命令。

var=$(awk -v line=$var2 'NR == line { print ; exit }' $file_path)