-1

I'm trying to read length characters from stdin in a bash script but I can't figure out how to pass length as a variable.

This is the script that should(tm) work:

for i in {1..9}
do
  read line
done

array=(${line})
length=${array[1]}

echo "$length" >> /home/ubuntu/test
read line
read -n $length line

echo "$line" >> /home/ubuntu/test

echo "done" >> /home/ubuntu/test

but, when I cat /home/ubuntu/test I don't see the data from the last read:

20558

done

However, if I replace read -n $length line with read -n 20558 line I get the expected data in the file.

How can I pass length as a variable to read?

edit

OK, I had a trailing newline in length. This works:

read -n ${length:0:-1} line
Andrew
  • 1
  • 1

1 Answers1

0

awk to the rescue!

awk 'NR==9{len=$2} NR==11{print substr($0,1,len); exit}'

based on your script, the second field on the 9th line defines the length to be read from the 11th line.

karakfa
  • 66,216
  • 7
  • 41
  • 56
  • That almost works but it's taking too long. This is a webserver responding to a github webhook and it times out if I read the last line (or use your `awk` script). It does work if I use `read -n` and specify the number of characters but only if I hard code the number of characters. – Andrew May 18 '16 at 20:58
  • OK, didn't know the use case. This reads the full line first and then chops it, not going to work for you. However, hard coding the number should not matter since bash will replace the variable first before invoking read. – karakfa May 18 '16 at 21:00
  • @Andrew What do you mean by "almost works"? Does it give the correct answer? How does your input data actually look and what are you trying to extract from it? – Mark Setchell May 18 '16 at 21:08
  • @MarkSetchell I get the data but the web client times out on the other end. – Andrew May 18 '16 at 22:01