cs:bash_language:arrays
Return to Home page
If you found any error, or if you want to partecipate to the editing of this wiki, please contact: admin [at] skenz.it
You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url: https://www.skenz.it/cs/bash_language/arrays?rev=1575455999&do=diff
Differences
This shows you the differences between two versions of the page.
— | cs:bash_language:arrays [2024/04/08 22:35] (current) – created - external edit 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== Arrays ====== | ||
+ | **Concepts: | ||
+ | Bash //arrays// and // | ||
+ | **Text:**\\ | ||
+ | Write an example that illustrates the use of bash //arrays// and // | ||
+ | In bash //array//, the index of the array must be an integer number. Some gaps may be present, i.e., indices can be not continuous.\\ | ||
+ | Instead, bash // | ||
+ | |||
+ | **Solution: | ||
+ | <code bash arrays.sh> | ||
+ | #!/bin/bash | ||
+ | # Example of use of the BASH arrays (and associative arrays) | ||
+ | |||
+ | # Classical array | ||
+ | echo " | ||
+ | vett2[3]=pasta | ||
+ | vett2[6]=bread | ||
+ | echo ${vett2[3]} | ||
+ | echo ${# | ||
+ | echo ${vett2[*]} | ||
+ | echo ${!vett2[*]} # Prints 3 6 | ||
+ | |||
+ | |||
+ | # Associative array | ||
+ | echo -e " | ||
+ | declare -A vett1 | ||
+ | |||
+ | vett1[stefano]=3 | ||
+ | nome=giulia | ||
+ | vett1[$nome]=pippo | ||
+ | |||
+ | echo ${vett1[stefano]} | ||
+ | echo ${vett1[" | ||
+ | echo ${# | ||
+ | echo ${vett1[*]} | ||
+ | echo ${!vett1[*]} | ||
+ | |||
+ | sum=0 | ||
+ | for name in ${!vett1[*]} | ||
+ | do | ||
+ | let sum=${vett1[$name]}+$sum | ||
+ | done | ||
+ | echo "Sum: $sum" | ||
+ | |||
+ | unset vett1 | ||
+ | echo ${# | ||
+ | </ | ||
+ | |||
+ | **Output: | ||
+ | <code bash> | ||
+ | $ ./arrays.sh | ||
+ | Classical array | ||
+ | pasta | ||
+ | 2 | ||
+ | pasta bread | ||
+ | 3 6 | ||
+ | |||
+ | Associative array | ||
+ | 3 | ||
+ | pippo | ||
+ | 2 | ||
+ | pippo 3 | ||
+ | giulia stefano | ||
+ | Sum: 3 | ||
+ | 0 | ||
+ | </ |
If you found any error, or if you want to partecipate to the editing of this wiki, please contact: admin [at] skenz.it
You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url: https://www.skenz.it/cs/bash_language/arrays?rev=1575455999&do=diff