Linux Shell script series tutorial (6): array and associated array
This article mainly introduces the Linux Shell script series (6): array and associated array, this article explains what arrays and associated arrays are, defines and prints common arrays, and defines and prints associated arrays. For more information, see
I. arrays and associated Arrays
Array is a very important component of Shell scripts. It stores multiple independent data as a collection with indexes. Ordinary Arrays can only use integers as array indexes. Associated Arrays can use integers as indexes or strings as indexes. In general, using strings for indexing is easier to understand. Bash introduced the correlated array after 4.0.
Ii. Define and print common Arrays
The array methods are as follows:
The Code is as follows:
# Listing all elements on a row
Array_var = (1 2 3 4 5 6)
# List them in the form of "index-value"
Array_var [0] = "test1"
Array_var [1] = "test2"
Array_var [2] = "test3"
Note: use parentheses in the first method. Otherwise, an error is returned.
The array element methods are as follows:
The 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 [*]} # the output value is 3.
Note: In ubuntu 14.04, the shell script must start #! Start with/bin/bash and run the script in bash test. sh mode.
3. Define print join Array
Define join Array
Any text can be used as an array index in the associated array. When defining an associated array, you must declare a variable as an associated array using the declaration statement before adding elements to the array. The procedure is as follows:
The Code is as follows:
Declare-A ass_array # declare an associated array
Ass_array = (["index1"] = index1 ["index2"] = index2) # nested "index-value" List Method
Ass_array ["index3"] = index3
Ass_array ["index4"] = index4
Echo $ {ass_array ["index1"]} # output is index1
Echo $ {ass_array ["index4"]}
Echo $ {! Ass_array [*]} # output index list
Echo $ {! Ass_array [@]} # output index list
Note: For normal arrays, the index list can still be listed using the above method. When declaring an associated array and adding an array element, you cannot add the dollar sign $