4

The length of an array in my bash shell script appears to be off by one. I have 11 elements in a text file that I am reading in to an array, but my array length seems to be 12.

(( count = 0 ))
while read students[$count] ; do
    (( count++ ))
done < students.dat

echo $count

ArrayLength=$((${#students[@]}))

echo $ArrayLength

This code outputs:

11
12

The 11 makes sense since the count increment occurs after the read occurs and starts with 0--indicating 11 elements read in.

But the 12 is mysterious.

Here is the data file:

Ann
Bob
Cindy
Dean
Emily
Frank
Ginger
Hal
Ivy
Justin
Karen

(names appear on their own lines, but I couldn't format it that way in this post)

I've double checked with multiple utilities and there is NOT a blank line at the end of the file, or any trailing spaces on any line.

8

The last read that fails to find more data will assign an empty string, so the number of entries is one more than your data. To check that use printf "'%s'\n" "${students[@]}".

  • 1
    Just to add more information to @Janis answer, if your run the script with bash -x students.sh you will see that the last read will increment in 1 the array: + read 'students[11]' + echo 11 11 + ArrayLength=12. Since it's reading the 11th position, the ArrayLength will be 12 at the end of the operations. – user34720 Mar 5 '15 at 19:01
  • Note that read fails when it doesn't read a newline character. It may fail and assign a non-empty string if the input ends in a non-terminated line. Like in printf foo | read line. – Stéphane Chazelas Mar 9 '15 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.