shell中数组的定义和操作
一、shell中数组的几种定义方式:
方法一:
[root@localhost ~]# array=(1 2 3) [root@localhost ~]# echo ${array[*]} 1 2 3
方法二:
[root@localhost ~]# array=([1]=one [2]=two [3]=three) [root@localhost ~]# echo ${array[*]} one two three
方法三:
[root@localhost ~]# array[0]=a [root@localhost ~]# array[1]=b [root@localhost ~]# array[2]=c [root@localhost ~]# echo ${array[1]}
方法四:动态定义数组变量,并使用命令的输出结果作为数组的内容
[root@localhost ~]# array=($(ls /home)) [root@localhost ~]# echo ${array[*]} student
二、数组的打印和输出
1)打印数组元素(其中@和*的作用相同,均是打印出所有元素)
[root@localhost ~]# array=(one two three) [root@localhost ~]# echo ${array[2]} three [root@localhost ~]# echo ${array[0]} one [root@localhost ~]# echo ${array[@]} one two three [root@localhost ~]# echo ${array[*]} one two three
2)打印元素个数
[root@localhost ~]# echo ${#array[*]} 3 [root@localhost ~]# echo ${#array[@]} 3
3)数组的赋值
#如果下标不存在,则自动添加一个新的元素,如果存在,则覆盖原来的值
[root@localhost ~]# array[3]=four [root@localhost ~]# echo ${array[*]} one two three four [root@localhost ~]# array[1]=hello [root@localhost ~]# echo ${array[*]} one hello three four
4)数组的删除
[root@localhost ~]# unset array[1] [root@localhost ~]# echo ${array[*]} one three four [root@localhost ~]# unset array [root@localhost ~]# echo ${array[*]}
5)数组内容截取和替换
[root@localhost ~]# array=(0 1 2 3 4) [root@localhost ~]# echo ${array[@]:1:3} 1 2 3 [root@localhost ~]# array=($(echo {a..z})) [root@localhost ~]# echo ${array[@]} a b c d e f g h i j k l m n o p q r s t u v w x y z [root@localhost ~]# echo ${array[@]:1:3} b c d [root@localhost ~]# array=(1 2 3 4 5) [root@localhost ~]# echo ${array[@]/3/three} 1 2 three 4 5
6)输出所有元素,遍历
a.标准的for循环
for(( i=0;i<${#array[@]};i++)) do #${#array[@]}获取数组长度用于循环 echo ${array[i]}; done;
b.for … in
遍历(不带数组下标): for element in ${array[@]} #也可以写成for element in ${array[*]} do echo $element done 遍历(带数组下标): for i in "${!arr[@]}"; do printf "%s\t%s\n" "$i" "${arr[$i]}" done
c.While循环法:
i=0 while [ $i -lt ${#array[@]} ] #当变量(下标)小于数组长度时进入循环体 do echo ${ array[$i] } #按下标打印数组元素 let i++ done