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.