2

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, 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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
arielle
  • 915
  • 1
  • 12
  • 29
  • It's not the first field of the first line, it's the first field of the line number `var2`, right? Did you try running with `set -x` to see what your command expands to? Where do you set your variables? – Benjamin W. Sep 02 '16 at 16:24
  • Yes, my mistake, it takes the first filed on line number var2. I define var2 earlier in the script. – arielle Sep 02 '16 at 16:30
  • What about replacing the long pipe with a single command? Perhaps something along the lines of this? `var=$(sed -ne "${var2}s/ .*//p;q" "$file_path")` (Notwithstanding whitespace issues of course.) – ghoti Sep 02 '16 at 16:41

1 Answers1

4

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)
Barmar
  • 741,623
  • 53
  • 500
  • 612