Arrays (Bash): verschil tussen versies
Naar navigatie springen
Naar zoeken springen
Regel 66: | Regel 66: | ||
* https://linuxhint.com/associative_array_bash/ | * https://linuxhint.com/associative_array_bash/ | ||
* https://stackoverflow.com/questions/11233825/multi-dimensional-arrays-in-bash | * https://stackoverflow.com/questions/11233825/multi-dimensional-arrays-in-bash | ||
+ | * https://stackoverflow.com/questions/3112687/how-to-iterate-over-associative-arrays-in-bash |
Versie van 3 jun 2022 10:15
Beginnetje:
#!/bin/bash a=(1 2 "Drie" 4 "Vijf") echo $a # Returns "1" - First item of the array echo $a[0] # Returns "1[0]" - The [0] part is treated as a literal echo ${a[0]} # Returns "1" echo ${a[@]} # Returns "1 2 3 4" - whole array
Nog een beginnetje:
a[0]="Nul" a[1]="Eén" echo $a # Toont alleen eerste element echo $a[0] # Output: Null[0] - Waarschijnlijk niet wat de bedoeling was echo ${a[1]} # OK
Multi-dimensional arrays
Bash ondersteunt geen multidimensionale arrays, maar je kunt een heel eind komen middels associative arrays
Associative arrays
- Associative arrays zijn arrays waarbij je elementen een eigen naam kunt geven. Je kunt ze daarnaast goed gebruiken voor multi-dimensionele arrays
- Associatieve arrays zijn nieuwe in Bash 4. Om te verifiëren welke versie van Bash je hebt:
bash --version
declare -A arr arr[0,0,0]="000" arr[0,0,1]="001" arr[0,1,0]="010" arr[0,1,1]="011" arr[1,0,0]="100" arr[1,0,1]="101" arr[1,1,0]="110" arr[1,1,1]="111" echo "${arr[0,0,0]} ${arr[0,0,1]} ${arr[0,1,0]} ${arr[0,1,1]}" echo "${arr[1,0,0]} ${arr[1,0,1]} ${arr[1,1,0]} ${arr[1,1,1]}"
Loop through array
Dit werkt. Merk op dat $i
de waarde van de cel bevat, niet de index:
array=( one two three ) for i in "${array[@]}" do echo "$i" done
Dit werkt niet zomaar voor associate array: De loop gaat door alle elementen, en niet door alleen de rijen.