I would like to set array elements with loop:
for i in 0 1 2 3 4 5 6 7 8 9
do
array[$i] = 'sg'
done
echo $array[0]
echo $array[1]
So it does not work. How to..?
There are two types of arrays that we can work with, in shell scripts. The default array that's created is an indexed array. If you specify the index names, it becomes an associative array and the elements can be accessed using the index names instead of numbers.
Arrays are important concepts in programming or scripting. Arrays allow us to store and retrieve elements in a list form which can be used for certain tasks. In bash, we also have arrays that help us in creating scripts in the command line for storing data in a list format.
Bash provides one-dimensional indexed and associative array variables. Any variable may be used as an indexed array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously.
Remove the spaces:
array[$i]='sg'
Also, you should access the elements as*:
echo ${array[0]}
See e.g. http://tldp.org/LDP/abs/html/arrays.html.
It should work if you had declared your variable as array, and print it properly:
declare -a array
for i in 0 1 2 3 4 5 6 7 8 9
do
array[$i]="sg"
done
echo ${array[0]}
echo ${array[1]}
See it in action here.
HTH
there is problem with your echo statement: give ${array[0]}
and ${array[1]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With