Establishment and application skills of Linux shell array

Time:2021-12-4

Linux shell is much more powerful than windows batch processing in programming, both in loop and operation. Data types cannot be compared. The following is a personal summary of some operations in array when using it.

1. Array definition

[[email protected] ~]$ a=(1 2 3 4 5)
[[email protected] ~]$ echo $a

A pair of parentheses indicates an array, and the array elements are separated by the “space” symbol.

2. Array reading and assignment

Length obtained:

[[email protected] ~]$ echo ${
#a[@]}

Use ${# array name [@ or *]} to get the array length

Read:

[[email protected]ntos5 ~]$ echo ${a[2]}
3
[[email protected] ~]$ echo ${a[*]}
1 2 3 4 5
Use ${array name [subscript]} to start with 0. The subscript is: * or @ to get the whole array content

Assignment:

[[email protected] ~]$ a[1]=100
[[email protected] ~]$ echo ${a[*]}
1 100 3 4 5

[[email protected] ~]$ a[5]=100
[[email protected] ~]$ echo ${a[*]}
1 100 3 4 5 100

It can be referenced and assigned directly through the array name [subscript]. If the subscript does not exist, a new array element will be added automatically

Delete:

[[email protected] ~]$ a=(1 2 3 4 5)
[[email protected] ~]$ unset a
[[email protected] ~]$ echo ${a[*]}
[[email protected] ~]$ a=(1 2 3 4 5)
[[email protected] ~]$ unset a[1]
[[email protected] ~]$ echo ${a[*]}
1 3 4 5
[[email protected] ~]$ echo ${
#a[*]}
4

Directly through the unset array [subscript], you can clear the corresponding elements, and clear the whole data without subscript.

3. Special use

Slice:

[[email protected] ~]$ a=(1 2 3 4 5)
[[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

Slice the original array directly through ${array name [@ or *]: starting position: length} and return a string separated by “space”. Therefore, if you add “()”, you will get the slice array. The above example: C is a new data.

Replace:

[[email protected] ~]$ a=(1 2 3 4 5)
[[email protected] ~]$ echo ${a[@]/3/100}
1 2 100 4 5
[[email protected] ~]$ echo ${a[@]}
1 2 3 4 5
[[email protected] ~]$ a=(${a[@]/3/100})
[[email protected] ~]$ echo ${a[@]}
1 2 100 4 5

The calling method is ${array name [@ or *] / find character / replace character} This operation will not change the original array content. If you need to modify it, you can look at the above example and redefine the data.

The above content is the Linux shell array establishment and use skills introduced by Xiaobian. I hope it will be helpful to you.