User Tools

Site Tools


cs:bash_language:arrays
Return to Home page

Arrays

Concepts:
Bash arrays and associative arrays.

Text:
Write an example that illustrates the use of bash arrays and associative arrays.
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 associative arrays are like hash maps, and the index of the array must be a string.

Solution:

arrays.sh
#!/bin/bash
# Example of use of the BASH arrays (and associative arrays)
 
# Classical array
echo "Classical array"
vett2[3]=pasta
vett2[6]=bread
echo ${vett2[3]}  # Prints pasta
echo ${#vett2[*]} # Prints 2
echo ${vett2[*]}  # Prints bread pasta
echo ${!vett2[*]} # Prints 3 6
 
 
# Associative array
echo -e "\nAssociative array"
declare -A vett1
 
vett1[stefano]=3
nome=giulia
vett1[$nome]=pippo
 
echo ${vett1[stefano]}  # Prints 3
echo ${vett1["giulia"]} # Prints pippo
echo ${#vett1[*]}       # Prints 2
echo ${vett1[*]}        # Prints pippo 3
echo ${!vett1[*]}       # Prints giulia stefano
 
sum=0
for name in ${!vett1[*]}
do
    let sum=${vett1[$name]}+$sum
done
echo "Sum: $sum"
 
unset vett1
echo ${#vett1[*]} # Prints 0 (because vett1 does not exist)

Output:

$ ./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?do=
/web/htdocs/www.skenz.it/home/data/pages/cs/bash_language/arrays.txt · Last modified: 2024/04/08 22:35 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki
Privacy Policy