1

I'm trying to fill an array with the lines in a file in bash. I do not understand what is happening here:

balter@exahead1:~$ declare -a a
balter@exahead1:~$ cat t.txt
a b
c d
e f
g h
balter@exahead1:~$ cat t.txt | while read -r line; do echo $line; a=("${a[@]}" "$line"); echo "$i: ${a[$i]}"; echo "${a[@]}"; ((i++)); done
a b
0: a b
a b
c d
1: c d
a b c d
e f
2: e f
a b c d e f
g h
3: g h
a b c d e f g h
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$

EDIT: Apparently it "works" if I redirect the file in rather than pipe it:

balter@exahead1:~$ while read -r line; do echo $line; a=("${a[@]}" "$line"); echo "$i: ${a[$i]}"; echo "${a[@]}"; ((i++)); done < t.txt
a b
0: a b
a b
c d
1: c d
a b c d
e f
2: e f
a b c d e f
g h
3: g h
a b c d e f g h
balter@exahead1:~$ echo "${a[@]}"
a b c d e f g h
balter@exahead1:~$

EDIT 2 @anubhava--what version of bash would I need? I tried your suggestion, and although we have mapfile it did not "work".

balter@exahead1:~$ bash --version
bash --version
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)   
balter@exahead1:~$ unset a
balter@exahead1:~$ a=()
balter@exahead1:~$ mapfile -t a < t.txt
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$

Neither did the 2nd method:

balter@exahead1:~$ unset a
balter@exahead1:~$ a=()
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$
balter@exahead1:~$ while IFS= read -r line; do a+=("$line"); done < t.txt
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$

EDIT 3

Both of the above methods "work" on my Mac running El Capitan.

codeforester
  • 39,467
  • 16
  • 112
  • 140
abalter
  • 9,663
  • 17
  • 90
  • 145

1 Answers1

1

You can just use builtin mapfile for this:

mapfile -t arr < file

If you are on older BASH version then you can use while loop like this:

arr=()

while IFS= read -r line; do
   arr+=("$line")
done < file
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Aha! We crossed. But you did teach me two things. (1) I've never heard of mapfile. (2) I did not know you could append arrays like that. What version of `bash` do I need? See my edits above. – abalter Jun 08 '17 at 19:23
  • `mapfile` was added in bash 4 – anubhava Jun 08 '17 at 20:32
  • My system has bash 4.2.46, but it did not fill the array using the method you suggested. However, my Mac is running 4.4.12, and it does "work". – abalter Jun 09 '17 at 01:33
  • I have BASH 4.3.46 and `mapfile` works. [See this link](http://wiki.bash-hackers.org/commands/builtin/mapfile) Some version of bash had bugs – anubhava Jun 09 '17 at 04:50