You can create an array by using the following command: arrayname=( value1 value2 …. valueN ). Here we create an array with 5 elements. myarray=( "string 1" "string 2" "string 3" "" "string4" )
or myarray=( [0]="string 1" [1]="string 2" [2]="string 3" [4]="string 4" )
The quotes are necessary if you have spaces in the elements. Note that only initialized elements will be counted. E.g. this ( [1]=1 [3]=3 ) would only return 2 as the number of elements although we used 3 as the last index. The missing elements have a null value
To get a list of the ‘used‘ indices, use: echo ${!myarray[*]}
To get the number of elements in an array, use: echo ${#myarray[@]}
or echo ${#myarray[*]}
To get a list of the elemets in an array, use: echo ${myarray[@]}
To get a particular element of the array, use:echo ${myarray[0]}
Remember that the first value has index number 0. => returns the first element of the arrayTo get the length of a particular element, use: echo ${#myarray[1]}
=> returns the length of the second element of the array.To un-initialise an element, use: unset ${myarray[2]}
=> sets the value of the element with index 2(3rd element) to null.
There are several ways to run over the content of an array. I prefer this ‘for loop‘, because it runs only over the initialized elements.
myarray=( [0]="string 1" [2]="string 2" [3]="string 3" [5]="" [6]="string4" )
for index in ${!myarray[*]}
do
echo "${myarray[$index]}"
done