shell(二)
shell数组
一、shell的定义
shell是若干数据的集合,不限制数组的大小,其中每一份数据都成为元素;
shell数组元素的下标也是从0开始。
获取数组中的元素要使用下表[ ]。下标可以是一个证书,也可以是一个结果为整数的表达式,下标必须大于等于0。
shell支支持一唯数组,不支持多维数组
二、shell中数组的表示方法
shell中,用括号()来表示数组,数组元素之间用空格来分隔。
array_name=(ele1 ele2 ele3…elen)
注意
赋值号=两边不能有空格,必须紧挨着数组名和数组元素。
如果想获取数组的元素个数:echo ${#a[*]}
方式一:
a=(1 2 3)
echo $a ###结果是显示数组a中的第一个元素
echo ${a[n]} ###显示数组中第n-1个元素,数组一般是从0开始编码,编码可以手动定义
==如果要获取数组的整个元素,可以使用echo ${a[*]}或者echo ${a[]@}
方式二:用小方括号将变量值括起来,采用键值对的方式将数组表示出来
[root@reg array]# b=([1]=one [2]=two [3]=three) ###将变量用小方括号引起来,此数组定义了数组元素是从1开始。
[root@reg array]# echo $b
[root@reg array]# echo ${b}
[root@reg array]# echo ${b[1]}
one
[root@reg array]# echo ${b[*]}
one two three
[root@reg array]# echo ${b[2]}
two
[root@reg array]# echo ${b[3]}
three
方式三:分别定义数组的元素
[root@reg array]# c[1]=one
[root@reg array]# c[2]=two
[root@reg array]# c[3]=three
[root@reg array]# c[0]=zero
[root@reg array]# echo $c
zero
[root@reg array]# echo ${c[0]}
zero
[root@reg array]# echo ${c[1]}
one
[root@reg array]# echo ${c[2]}
two
[root@reg array]# echo ${c[3]}
three
[root@reg array]# echo ${c[*]}
zero one two three
[root@reg array]#
方式四:动态定义数组变量
可以使用的新的变量来赋值
[root@reg test]# test=($(ls .))
[root@reg test]# echo ${test[*]}
1.test 2.test 3.test
[root@reg test]#
数组元素的删除
1、删除某一个元素
[root@reg test]# echo ${a[*]}
1 2 3
[root@reg test]# echo ${#a[*]}
3
[root@reg test]# unset ${a[1]}
-bash: unset: `2': not a valid identifier
[root@reg test]# unset a[1]
[root@reg test]# echo ${#a[*]}
2
[root@reg test]# echo ${a[*]}
1 3
[root@reg test]#
2、清空数组的整个元素
[root@reg test]# unset a
[root@reg test]# echo ${a[*]}
[root@reg test]#
数组元素的截取和替换
一、数组元素的截取:
截取下标1到3号的元素
[root@reg test]# a=(1 2 3 4 5)
[root@reg test]# echo ${a[@]:1:3}
2 3 4
二、数组元素的替换
将数组中的某一个元素替换为另一个元素
[root@reg test]# a=(1 2 3 4 5 1 1 2 3 4 2 4 4)
[root@reg test]# echo ${a[*]/1/a}
a 2 3 4 5 a a 2 3 4 2 4 4
[root@reg test]# echo ${a[*]/4/b}
1 2 3 b 5 1 1 2 3 b 2 b b
[root@reg test]#
数组例题
1、使用循环批量输出数组的元素
2、通过竖向列举法定义数组元素并列出
#!/bin/bash
a=(linux windows mac deban)
for ((i=0;i<${#a[*]};i++))
do
echo "This is number $i,and the content is: ${a[i]}"
done
echo "a len is:${#a[*]}"
3、将命令结果作为数组的元素定义并打印
#!/bin/bash
dir=($(ls /func))
for ((i=0;i<${#dir[*]};i++))
do
echo "This is NO.$i,filename is ${dir[$i]}"
done
小试牛刀面试题:
利用bashfor循环打印下面这句话中字母数不大于6的单词
#!/bin/bash
a=(I am a student from china)
for ((i=0;i<${#a[*]};i++))
do
if [ ${#a[$i]} -le 6 ]
then
echo "The word of NO.$i is small than 6,and the word is ${a[i]}"
fi
done
执行结果是
The word of NO.0 is small than 6,and the word is I
The word of NO.1 is small than 6,and the word is am
The word of NO.2 is small than 6,and the word is a
The word of NO.4 is small than 6,and the word is from
The word of NO.5 is small than 6,and the word is china