一、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]}
b
方法四:动态定义数组变量,并使用命令的输出结果作为数组的内容
[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)输出所有元素
#!/bin/bash
array=(9 6 7 5 9 1)
for((i=0;i<=${#array[@]}-1;i++))
do
echo ${array[i]}
done
到此这篇关于shell中数组的定义及操作的文章就介绍到这了,更多相关shell 数组定义及操作内容请搜索aitechtogether.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持aitechtogether.com!