Bash Array
Bash Array – An array is a collection of elements. Unlike in many other programming languages, in bash, an array is not a collection of similar elements. Since bash does not discriminate string from a number, an array can contain a mix of strings and numbers.
Bash Array Tutorials
The following tutorials deal with the individual concepts of an array in details with well explained examples.
Basics
- Bash – Initialize Array
- Bash – Length/Size of Array
- Bash – Access Elements(s) of Array using Index
- Bash – Print All Elements of Array in Single Line to Console
Looping Scenarios
- Bash – Loop through Array Elements
- Bash – Loop through Array Indices
- Bash Array – While Loop
- Bash Array – For Loop
Find / Check
Modifications
- Bash – Update Element of an Array at Specific Index
- Bash – Append Element(s) to Array
- Bash – Append an Array to another Array
- Bash – Slice an Array
Bash Array Declaration
To declare a variable as a Bash Array, use the keyword declare
and the syntax is
declare -a arrayname
Example
In the following script, we declare an array with name fruits
.
declare -a fruits
Bash Array Initialization
To initialize a Bash Array, use assignment operator =
, and enclose all the elements inside braces ()
. The syntax to initialize a bash array is
arrayname=(element1 element2 element3)
Example
In the following script, we initialize an array fruits
with three elements.
fruits=("apple" "banana" "cherry")
Access elements of Bash Array
We can access elements of a Bash Array using the index.
echo ${ARRAY_NAME[2]}
Example
In the following script, we access elements of array fruits
with indices.
fruits=("apple" "banana" "cherry")
echo ${fruits[0]}
echo ${fruits[1]}
Print Bash Array with Indices and Details
To print all the elements of a bash array with all the index and details use declare
with option p
.
declare -p arrayname
Example
fruits=("apple" "banana" "cherry")
declare -p fruits
Output
declare -a fruits='([0]="apple" [1]="banana" [2]="cherry")'
Loop through Elements of Array using For Loop
We can loop through elements of array using for loop, as shown in the following example.
Example
fruits=("apple" "banana" "cherry")
for element in "${fruits[@]}";
do
echo $element
done
Output
apple
banana
cherry
Conclusion
Concluding this Bash Tutorial, we have learnt how to declare, initialize and access Bash Arrays, with the help of examples.