1.数组定义方法
方法1:
[root@localhost ~]# array=(1 2 3)
[root@localhost ~]# echo ${array[*]}
1 2 3
方法2:
[root@localhost ~]# array=([1]=one [2]=two [3]=three)
[root@localhost ~]# echo ${array[*]}
one two three
方法3:
[root@localhost ~]# array[0]=a
[root@localhost ~]# array[1]=b
[root@localhost ~]# array[2]=c
[root@localhost ~]#
[root@localhost ~]# echo ${array[1]}
b
方法4:动态定义数组变量,并使用命令的输出结果作为数组的内容
[root@localhost Desktop]# array=($(ls /mnt))
[root@localhost Desktop]# echo ${array[*]}
harry.sql mysqldump natasha.sql tom.sql
2.数组的打印和输出
1)打印数组元素
[root@localhost ~]# array=(one two three)
[root@localhost ~]# echo ${array[0]}
one
[root@localhost ~]# echo ${array[1]}
two
[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 Desktop]# array[4]=four
[root@localhost Desktop]# echo ${array[*]}
a b c three four
[root@localhost Desktop]# array[2]=five
[root@localhost Desktop]# echo ${array[*]}
a b five three four
4)数组的删除
[root@localhost Desktop]# unset array[1]
[root@localhost Desktop]# echo ${array[*]}
1 3 1 1
[root@localhost Desktop]# unset array
[root@localhost Desktop]# echo ${array[*]}
5)数组内容截取和替换
[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 ~]#
[root@localhost ~]# echo ${array[@]:1:3}
b c d
替换
[root@localhost ~]# array=(1 2 3 1 1)
[root@localhost ~]#
[root@localhost ~]# echo ${array[@]/1/b}
b 2 3 b b
练习1:循环输出数组元素
#!/bin/bash
#循环输出数组元素
array=(1 2 3 4 5)
for ((i=0;i<${#array[*]};i++))
do
echo ${array[i]}
done
脚本执行结果如下:
练习2:利用for循环打印下面这句话中字母个数不大于6的单词
I am westos teacher welcom to westos training class
vim 01.sh
#!/bin/bash
array=( I am a westos teacher welcome to westos training class )
for ((i=0;i<${#array[*]};i++))
do
if [ ${#array[i]} -le 6 ];then
echo "${array[i]}"
fi
done
脚本执行结果如下: