Bash Array
An array can be defined as a collection of similar type of elements. Unlike most of the programming languages,
arrays in bash scripting need not be the collection of similar elements. Since Bash does not discriminate the
string from a number, an array may contain both strings and numbers.
Bash does not provide support for the multidimensional arrays; we cannot have the elements which are arrays
in themself. Bash provides support for one-dimensional numerically indexed arrays as well as associative
arrays. To access the numerically indexed array from the last, we can use negative indices. The index of '-1'
will be considered as a reference for the last element. We can use several elements in an array.
Bash Array Declaration
Arrays in Bash can be declared in the following ways:
Creating Numerically Indexed Arrays
We can use any variable as an indexed array without declaring it.
To explicitly declare a variable as a Bash Array, use the keyword 'declare' and the syntax can be defined as:
declare -a ARRAY_NAME
where,
ARRAY_NAME indicates the name that we would assign to the array.
Note: Rules of naming a variable in Bash are the same for naming an array.
A general method to create an indexed array can be defined in the following form:
ARRAY_NAME[index_1]=value_1
ARRAY_NAME[index_2]=value_2
ARRAY_NAME[index_n]=value_n
where keyword 'index' is used to define positive integers.
Creating Associative Arrays
Unlike numerically indexed arrays, the associative arrays are firstly declared. We can use the keyword 'declare'
and the -A (uppercase) option to declare the associative arrays. The syntax can be defined as:
declare -A ARRAY_NAME
, A general method to create an associative array can be defined in the following form:
declare -A ARRAY_NAME
ARRAY_NAME[index_foo]=value_foo
ARRAY_NAME[index_bar]=value_bar
ARRAY_NAME[index_xyz]=value_xyz
where index_ is used to define any string.
We can also write the above form in the following way:
declare -A ARRAY_NAME
ARRAY_NAME=(
[index_foo]=value_foo
[index_bar]=value_bar
[index_xyz]=value_xyz
)
Bash Array Initialization
To initialize a Bash Array, we can use assignment operator (=), by specifying the list of the elements within
parentheses, separated by spaces like below:
ARRAY_NAME=(element_1st element_2nd element_Nth)
Note: Here, the first element will have an index 0. Also, there should be no space around the assignment operator (=).
Access Elements of Bash Array
To access the elements of a Bash Array, we can use the following syntax:
echo ${ARRAY_NAME[2]}
Print Bash Array
We can use the keyword 'declare' with a '-p' option to print all the elements of a Bash Array with all the indexes
and details. The syntax to print the Bash Array can be defined as:
declare -p ARRAY_NAME