SoFunction
Updated on 2025-03-10

Linux Shell Script Series Tutorials (VI): Arrays and Associated Arrays

1. Arrays and associative arrays

Arrays are a very important component of shell scripts, which store multiple independent data into a collection with the help of indexes. Ordinary arrays can only use integers as array indexes, and associative arrays can not only use integers as indexes, but also strings as indexes. Usually, using strings as indexing is easier to understand. Bash starts introducing associative arrays after 4.0.

2. Define printing ordinary arrays

There are several methods for arrays:

Copy the codeThe code is as follows:

#List all elements on a line
array_var=(1 2 3 4 5 6)

#List one by one in the form of "index-value"
array_var[0]="test1"
array_var[1]="test2"
array_var[2]="test3"

Note: The first method must use parentheses, otherwise an error will be reported later.

There are several methods for array elements:

Copy the codeThe code is as follows:

echo ${array_var[0]}           #The output result is test1
index=2
echo ${array_var[$index]}   #The output result is test3
echo ${array_var[*]}          #Output all array elements
echo ${array_var[@]}           #Output all array elements
echo ${#array_var[*]}           #Output value is 3

Note: In ubuntu 14.04, the shell script should start with #!/bin/bash, and the script is executed in bash.

3. Define printing associative arrays

Define an associative array
In an associative array, any text can be used as an array index. When defining an associative array, you first need to declare a variable as an associative array using a declaration statement, and then you can add elements to the array. The process is as follows:

Copy the codeThe code is as follows:

declare -A ass_array                                                                                                                           �
ass_array=(["index1"]=index1 ["index2"]=index2)#Inline "Index-value" list method

ass_array["index3"]=index3
ass_array["index4"]=index4

echo ${ass_array["index1"]}                                                                                                                      �
echo ${ass_array["index4"]}

echo ${!ass_array[*]}                                                        �
echo ${!ass_array[@]}                                                        �


Note: For ordinary arrays, you can still list the index list using the above method. When declaring the associative array and adding array elements, you cannot add the dollar sign $ in front of it.