简体   繁体   English

仅当非交互式运行bash脚本时,出现错误“猫:写入错误:管道损坏”

[英]Getting error “cat: write error: Broken pipe” only when running bash script non-interactively

I wrote a bash script where I define a variable like this: 我写了一个bash脚本,在其中定义了这样一个变量:

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

Where $file_path simply contains the path to a file and $var2 is an int, eg, 1 or 2. The variable is therefore assigned the value of the first field of line number var2 of the file. 其中$file_path仅包含文件路径,而$var2是整数,例如1或2。因此,为变量分配了文件行号var2的第一个字段的值。

It works perfectly fine when I run this from the command line. 当我从命令行运行此程序时,它工作得很好。 However, when running the script containing this command, I get the error 但是,运行包含此命令的脚本时,出现错误

cat: write error: Broken pipe cat:写入错误:管道损坏

Any idea why that is? 知道为什么吗?

There's no need to use cat , since head takes a filename argument. 不需要使用cat ,因为head使用文件名参数。

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

Actually, there's no need to use any of those commands. 实际上,不需要使用任何这些命令。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当bash子脚本与父脚本一起以交互方式(由终端)调用时退出,而不是由cron以非交互方式被调用时退出 - bash child script exits along with parent script when parent invoked interactively / by terminal, but not when invoked non-interactively / by cron 为什么我很少收到“cat: write error: Broken pipe” - Why am I getting “cat: write error: Broken pipe” rarely and not always 写错误:管道坏了 - write error: Broken pipe C:“写:管道损坏”错误 - C: “write: Broken pipe” error 运行bash脚本时出现Bash错误太多参数 - Getting Bash error too many arguments while running bash script 如何在shell或Perl脚本中发出“模块加载”(即非交互式) - How to issue “module load” in a shell or Perl script (i.e., non-interactively) 以非交互方式运行 rustup 的 curl-fetched 安装程序脚本 - run rustup's curl-fetched installer script non-interactively 仅当函数的返回值等于“ Value”时,gdb才能有条件地非交互地中断函数吗? - Can gdb conditionally break non-interactively on function only if the function's return value is equal to “Value”? 管道破裂错误时,CPU使用率增加 - CPU usage increases when broken pipe error 在Gnome Scheduler中运行Bash脚本时出现奇怪的Bash错误 - Odd Bash Error When Running Bash Script In Gnome Scheduler
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM