Динамические массивы

Массивы и коллекции / Массивы

count=5

#every bash array is dynamic: it grows with each new element,
#its size is not set in advance
lstInt=()
for ((i = 0; i < count; i++)); do
    lstInt+=(0)
done
lstInt[0]=1
#lstInt is (1 0 0 0 0)

squares=()
for i in {1..10}; do
    squares+=($((i * i)))
done
squaresCount=${#squares[@]}
#squaresCount is 10, squares[9] is 100

#an index far past the end makes no room for the elements between:
#the array is sparse and keeps only what was set
sparse=()
sparse[1000000]=1
sparseCount=${#sparse[@]}
#sparseCount is 1

echo "lstInt is (${lstInt[*]})"
echo "squaresCount is $squaresCount"
echo "squares[9] is ${squares[9]}"
echo "sparseCount is $sparseCount"