Introduction to Arrays
Bash provides only one-dimensional arrays, and does not qualify the size of the array. Similar to the C language, the subscript of an array element is numbered starting with 0. Gets the elements in the array to take advantage of the subscript. The subscript can be an integer or an arithmetic expression whose value should be greater than or equal to 0. You can assign values to an array variable using an assignment statement.
Array Assignment
Subscript Assignment
$ students[0]=Jack$ students[1]=Alex$ students[2]=Amy
You can also use declare
explicit declaration of an array:
$ declare -a 数组名
Direct Assignment
$ students=(Jack Alex Amy)或$ declare -a studentds=(Jack Alex Amy)
Command Assignment
The output format of the command is as follows
$ lsDesktop Downloads Pictures Templates virtualenv $ arr=($(ls))
Dictionary Assignment
Dictionary can be declare -A
declared by command
$ declare -A dict=([key1]=val1 [key2]=val2)
accessing arrays
创建数组$ students=(Jack Alex Amy)
Access by subscript
$ echo ${students[0]}Jack$ echo ${students[1]}Alex$ echo ${students[2]}Amy
List all elements
$ echo ${students[@]}Jack Alex Amy或$ echo ${students[*]}Jack Alex Amy
@
Both symbols *
and symbols can list all elements
Other operations of the array
Get array length
$ echo ${#students[@]}3
Print array subscript
$ echo ${!students[@]}0 1 2
You can also print the dictionary key value
$ declare -A dict=([key1]=val1 [key2]=val2)$ echo ${!dict[@]}key2 key1
Delete an array
$ unset 数组名
Introduction to Shell Array usage