Ich versuche, ein Array mit den Zeilen in einer Datei in bash zu füllen. Ich verstehe nicht, was hier geschieht:Bash-Array füllt Schleife nicht aus Datei
[email protected]:~$ declare -a a
[email protected]:~$ cat t.txt
a b
c d
e f
g h
[email protected]:~$ 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
[email protected]:~$ echo "${a[@]}"
[email protected]:~$
EDIT: Anscheinend es "funktioniert", wenn ich die Datei in anstatt Rohr umleiten:
[email protected]:~$ 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
[email protected]:~$ echo "${a[@]}"
a b c d e f g h
[email protected]:~$
EDIT 2 @ Anubhava - welche Version von bash
würde ich brauchen? Ich habe Ihren Vorschlag versucht, und obwohl wir mapfile
haben, hat es nicht "funktioniert".
[email protected]:~$ bash --version
bash --version
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)
[email protected]:~$ unset a
[email protected]:~$ a=()
[email protected]:~$ mapfile -t a < t.txt
[email protected]:~$ echo "${a[@]}"
[email protected]:~$
Ebenso wenig wie die zweite Methode:
[email protected]:~$ unset a
[email protected]:~$ a=()
[email protected]:~$ echo "${a[@]}"
[email protected]:~$
[email protected]:~$ while IFS= read -r line; do a+=("$line"); done < t.txt
[email protected]:~$ echo "${a[@]}"
[email protected]:~$
EDIT 3
Sowohl die oben genannten Methoden "Arbeit" auf meinem Mac läuft El Capitan.
Aha! Wir kreuzten. Aber du hast mir zwei Dinge beigebracht. (1) Ich habe noch nie von Mapfile gehört. (2) Ich wusste nicht, dass Sie solche Arrays anhängen können. Welche Version von 'bash' brauche ich? Siehe meine Änderungen oben. – abalter
'mapfile' wurde in bash hinzugefügt 4 – anubhava
Mein System hat bash 4.2.46, aber es füllte das Array nicht mit der von Ihnen vorgeschlagenen Methode. Mein Mac läuft jedoch mit 4.4.12, und es funktioniert ". – abalter