Initialise Array
To initialise array with elements in Bash, use assignment operator =
, and enclose all the elements inside braces ()
separated by spaces in between them. We may also specify the index for each element in the array.
Syntax
The syntax to initialise an array with elements is
</>
Copy
arrayname=(element1 element2 elementN)
The syntax to initialise an array with elements and their respective indices is
</>
Copy
arrayname=([index1]=element1 [index2]=element2 [indexN]=elementN)
Examples
Initialise Array with Elements
In this tutorial, we will initialise an array arr
with three string values.
Example.sh
</>
Copy
arr=("apple" "banana" "cherry")
echo ${arr[@]}
Output
</>
Copy
apple banana cherry
Initialise Array with Elements and their Indices
In this tutorial, we will initialise an array arr
with three string values and also the index for each of the element.
Example.sh
</>
Copy
arr=([2]="apple" [3]="banana" [4]="cherry")
echo ${arr[2]}
echo ${arr[3]}
Output
</>
Copy
apple
banana
Conclusion
In this Bash Tutorial, we have learnt how to initialise an array in Bash shell.