arielle arielle - 1 year ago 84
Linux Question

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)

simply contains the path to a file and
is an int, e.g., 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?

Any advice is really appreciated!

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download