定义数组
- 等号紧跟数组名和值
- 数组值用小圆括号括起来
- 各值之间用空格分隔
arr=(a b c d e f)
调用数组
输出数组第一个元素
[root@yihelinux ~]# echo ${arr[0]}
a
输出数组全部元素
[root@yihelinux ~]# echo ${arr[@]}
a b c d e f
[root@yihelinux ~]# echo ${arr[*]}
a b c d e f
统计数组元素个数
[root@yihelinux ~]# echo ${#arr[*]}
6
输出所有元素下标
[root@yihelinux ~]# echo ${!arr[*]}
0 1 2 3 4 5
添加数组元素
通过下标添加,序号从0开始,顺序按下标排序
[root@yihelinux ~]# arr[6]=g
[root@yihelinux ~]# arr[7]=h
[root@yihelinux ~]# arr[9]=j
[root@yihelinux ~]# arr[8]=i
[root@yihelinux ~]# echo ${arr[@]}
a b c d e f g h i j
[root@yihelinux ~]#
可以将命令值直接赋值给数组
[root@yihelinux ~]# num=($(df -Th|tail -n +2|awk '{print $6}'|tr -d "%"))
[root@yihelinux ~]# echo ${num[@]}
34 0 0 2 0 53 0
[root@yihelinux ~]#
一个简单的小脚本
将函数传入的参数用数组保存,用函数输出
#!/bin/bash
name=($@)
parry(){
echo "第${i}个参数是:${name[${i}]}"
}
for ((i=0;i<${#name[*]};i++))
do
parry ${i}
done
echo "总共有${#name[@]}个位置参数"
echo "所有的位置参数内容如下:${name[@]}"
输出如下:
[root@yihelinux lianxi]# bash parry.sh a b c d e f
第0个参数是:a
第1个参数是:b
第2个参数是:c
第3个参数是:d
第4个参数是:e
第5个参数是:f
总共有6个位置参数
所有的位置参数内容如下:a b c d e f