Arrays are not used very often in the shell, but are very useful, let's take a look at some of the uses of arrays in the shell:
- Define array a= (1 2 3 4 5); Print array echo ${a[@]}
The contents of the array can be either numbers or letters, as shown in the following example:[[email protected] ~]# a=(1 2 3 4 5)[[email protected] ~]# echo $a //可以看到使用这种方式返回不了数组的值1[[email protected] ~]# echo ${a[@]}1 2 3 4 5
- echo ${#a [@]} Gets the number of elements in the array
[[email protected] ~]# echo ${#a[@]} //在打印数组命令中嵌入一个#号5[[email protected] ~]#
- echo ${a[2]} reads the third element, array starting from 0
[[email protected] ~]# echo ${a[2]} //读取数组第三个元素,下标为23[[email protected] ~]# echo ${a[1]} //读取数组第二个元素,下标为12[[email protected] ~]# echo ${a[0]} //读取数组第一个元素,下标为0,下标都是从0开始的1[[email protected] ~]#
- echo ${a[*]} equals ${a[@]} displays the entire array
[[email protected] ~]# echo ${a[*]} //使用*或@来表示数组的所有元素1 2 3 4 5[[email protected] ~]#
- Array element Assignment command a[1]=100; Echo ${a[@]}
[[email protected] ~]# a[1]=100 [[email protected] ~]# echo ${a[1]}100[[email protected] ~]# echo ${a[*]}1 100 3 4 5[[email protected] ~]#
- a[5]=2; Echo ${a[@]} An element is added automatically if the subscript does not exist
[[email protected] ~]# a=(1 2 3 4 5)[[email protected] ~]# echo ${a[*]}1 2 3 4 5[[email protected] ~]# a[5]=6[[email protected] ~]# echo ${a[*]}1 2 3 4 5 6[[email protected] ~]#
- The deletion of the array uset A; Unset A[1]
[[email protected] ~]# unset a[4] //删除其中某一个元素,这里删除的是第5个元素[[email protected] ~]# echo ${a[*]}1 100 3 4[[email protected] ~]# unset a //删除数组a中的所有元素[[email protected] ~]# echo ${a[*]} [[email protected] ~]#
- array Shard
- a= (
seq 1 5
)
- Echo ${a[@]:0:3} starts with the first element, intercepts 3
[[Email p Rotected] ~]# a= (' seq 1 ') [[email protected] ~]# echo ${a[*]}1 2 3 4 5 6 7 8 9 101 2 3
- Echo ${a[@]:1:4} starts with the second element, intercepts 4
2 3 4[[email protected] ~]#
- Echo ${a[@]:0-3:2} Starting from the 3rd element, intercept 2
[[email protected] ~]# echo ${a[@]}1 2 3 4 5 6 7 8 9 10[[email protected] ~]# echo ${a [@]:0-3:2}//Here with 0-3 for the 3rd element, 0 cannot omit 8 9[[email protected] ~]#
- Array substitution
- Echo ${A[@]/8/6}
[[email protected] ~]# a=(`seq 1 10`) [[email protected] ~]# echo ${a[@]}1 2 3 4 5 6 7 8 9 10[[email protected] ~]# echo ${a[@]/8/6} //将8替换为61 2 3 4 5 6 7 6 9 10[[email protected] ~]# echo ${a[@]} //替换后a的值并未发生变化1 2 3 4 5 6 7 8 9 10
- A= (${A[@]/8/6})
[[email protected] ~]# echo ${a[@]}1 2 3 4 5 6 7 8 9 10[[email protected] ~]# a=(${a[@]/8/6}) //将8替换为6后,将结果赋值给数组a[[email protected] ~]# echo ${a[@]} //这时a的值发生了变化1 2 3 4 5 6 7 6 9 10[[email protected] ~]#
Arrays in the shell