简体   繁体   中英

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:

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.

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

Any idea why that is?

There's no need to use cat , since head takes a filename argument.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM