Shell scripts are extremely important in operations, and the use of arrays in shell scripts is a very useful aspect in both looping and computing.
Here are some operations on the array aspects of the shell script to record here, hoping to help interested friends ~
1. Array definitions
[[email protected] ~]# a= (1 2 3 4 5 6 7 8)
[Email protected] ~]# echo $a
1
A pair of parentheses indicates an array, and the elements of the array are separated by a "space" symbol.
2. Array reading and Assignment
1) Get the length :
[[email protected] ~]# echo ${#a [@]}
8
[[email protected] ~]# echo ${#a [*]}
8
Use ${#数组名 [@ or *]} to get the array length
2) Read:
[[email protected] ~]# echo ${a[4]}
5
[[email protected] ~]# echo ${a[*]}
1 2 3 4 5 6 7 8
Using the ${array name [subscript]} subscript is starting from 0 subscript is: * or @ Get the entire array contents
3) Assign value:
[Email protected] ~]# a[1]=100
[[email protected] ~]# echo ${a[*]}
1 100 3 4 5 6 7 8
[Email protected] ~]# a[5]=140
[[email protected] ~]# echo ${a[*]}
1 100 3 4 5 140 7 8
It can be referenced directly by the array name [subscript], and if the subscript does not exist, a new array element is added automatically
4) Delete:
[[email protected] ~]# a= (1 2 3 4 5 6 7 8)
[Email protected] ~]# unset a
[[email protected] ~]# echo ${a[*]}
[[email protected] ~]# a= (1 2 3 4 5 6 7 8)
[Email protected] ~]# unset a[1]
[[email protected] ~]# echo ${a[*]}
1 3 4 5 6 7 8
[[email protected] ~]# echo ${#a [*]}
7
Directly through: unset array [subscript] can clear the corresponding element, without subscript, clear the entire data.
3. Special use
1) Shard:
[[email protected] ~]# a= (1 2 3 4 5 6 7 8)
[[email protected] ~]# echo ${a[@]:0:3}
1 2 3
[[email protected] ~]# echo ${a[@]:1:4}
2 3 4 5
[[email protected] ~]# c= (${a[@]:1:4})
[[email protected] ~]# echo ${#c [@]}
4
[[email protected] ~]# echo ${c[*]}
2 3 4 5
Directly through the ${array name [@ or *]: Start position: Length} Slice the original array, return is a string, the middle with "space" separate, so if you add "()", will get the slice array, the above example: C is a new data.
2) Replace:
[[email protected] ~]# a= (1 2 3 4 5 6 7 8)
[[email protected] ~]# echo ${a[@]/3/100}
1 2 100 4 5 6 7 8
[[email protected] ~]# echo ${a[@]}
1 2 3 4 5 6 7 8
[[email protected] ~]# a= (${a[@]/3/100})
[[email protected] ~]# echo ${a[@]}
1 2 100 4 5 6 7 8
The call method is: ${array name [@ or *]/find character/substitution character} This operation will not change the original array contents, if you need to modify, you can see the above example, redefine the data.
Arrays-Introduction to basic usage in shell scripts