Linux shell array creation and use skills

  

linux shell is much more powerful than windows batch in programming, whether it is looping or computing. The data types are incomparable. The following is a summary of some of the operations in the array when the individual is using it.


1. Array definition


[chengmo@centos5 ~]$ a=(1 2 3 4 5)[chengmo@centos5 ~] $ echo $a1


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


2. Array reading and assignment • get length:

[chengmo@centos5 ~]$ echo ${#a[@]}5

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

[chengmo@centos5 ~]$ echo ${a[2]} 3

[chengmo@centos5 ~]$ echo ${a[*]} 1 2 3 4 5

With ${array name[subscript]} The subscript is starting from 0 and the subscript is: * or @Get the entire array contents • Assignment:

[chengmo@centos5 ~]$ a[1]=100

[chengmo@centos5 ~]$ echo ${a[*]} 1 100 3 4 5


[chengmo@centos5 ~]$ a[5]=100 [chengmo@centos5 ~]$ echo ${a[*]}

1 100 3 4 5 100

You can assign a reference directly to the array name [subscript]. If the subscript does not exist, automatically add a new array element • Delete:

[chengmo@centos5 ~]$ a=(1 2 3 4 5)[chengmo@centos5 ~]$ unset a[chengmo@centos5 ~]$ echo ${a[*]}

[chengmo@centos5 ~]$ a=(1 2 3 4 5)[chengmo@centos5 ~]$ unset a[1] [chengmo@centos5 ~]$ echo ${a[*]} 1 3 4 5[chengmo@centos5 ~]$ Echo ${#a[*]}4

Directly through: unset array [subscript] To clear the corresponding element, without subscripts, clears the entire data.



3.Special use •Slice:

[chengmo@centos5 ~]$ a=(1 2 3 4 5)[ ,null,null,3],Chengmo@centos5 ~]$ echo ${a[@]:0:3}1 2 3[chengmo@centos5 ~]$ echo ${a[@]:1:4}2 3 4 5

[chengmo@centos5 ~]$ c=(${a[@]:1:4})[chengmo@centos5 ~]$ echo ${#c[@]}4[chengmo@centos5 ~]$ echo ${c [*]} 2 3 4 5

Directly through ${array name[@ or*]: starting position: length} slice the original array, return a string, separated by “space” So if you add ”()”, you will get a sliced ​​array. The above example: c is a new data. •Replace:

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

The calling method is: ${array name[@ or*]/lookup character/replacement character} This operation does not change the original array content, if it needs to be modified You can redefine the data by looking at the above example.


From the above, you can find that the array of linux shell is very powerful, and the common operations are more than enough.

Copyright © Windows knowledge All Rights Reserved