本文索引:
- shell中的函数
- shell中的数组
- 告警系统需求分析
shell中的函数
shell作为一种编程语言,必然有函数。函数可以大大减少代码,提高代码复用率。 shell中的函数就是把一段代码整理到了一个小单元中,并给这个小单元起一个名字,当用到这段代码时直接调用这个小单元的名字即可。
格式
1function name() { 2 commands 3}
函数必须复制在脚本中调用该函数的代码之前!
-
实例1
input返回脚本的参数
#!/bin/bash input() { echo $1 $2 $# $0 }
input 1 a b
[root@castiel-Lu shell]# sh -x fun1.sh
- input 1 a b
- echo 1 a 3 fun1.sh 1 a 3 fun1.sh
$0 脚本本身
脚本内改为 input $1 $2 $3,在执行时加上参数例如sh fun1.sh 1 a b,显示结果一致
-
实例2
sum函数定义2个数相加
#!/bin/bash sum() { s=$[$1+$2] echo $s } sum $1 $2
[root@castiel-Lu shell]# sh -x fun2.sh 1 2
- sum 1 2
- s=3
- echo 3 3
-
实例3
#!/bin/bash ip() { ifconfig |grep -A1 "$1 " |awk '{print $2}'' } read -p "Please input the eth name: " e myip=
ip $eecho "$e address is $myip"[root@castiel-Lu shell]# sh -x fun3.sh
- read -p 'Please input the eth name: ' e Please input the eth name: ens33 ++ ip ens33 ++ grep -A1 'ens33: ' ++ awk '/inet/ {print $2}' ++ ifconfig
- myip=172.16.132.248
- echo 'ens33 address is 172.16.132.248' ens33 address is 172.16.132.248
写shell脚本需要不断的调整代码已完成最终效果.
1# 判断网卡是否是系统内的,如果是系统内的则判断是否网卡是否有ip 2ifconfig $1 2&> /dev/null 3if [ $? -ne 0 ] 4then 5 echo "Wrong interface!" 6else 7 ip=`ifconfig |grep -A1 "$1 " |awk '{print $2}''` 8 if [ -z $ip ] 9 then 10 echo "there is no ip in this interface" 11 fi 12fi
shell中的数组
定义数组
[root@castiel-Lu ~]# a=(1 2 3 4 5)
列出所有的值
1[root@castiel-Lu ~]# echo ${a[@]} 21 2 3 4 5 3[root@castiel-Lu ~]# echo ${a[*]} 41 2 3 4 5
检索,从0开始
1[root@castiel-Lu ~]# echo ${a[0]} 21
列表内参数的个数
1[root@castiel-Lu ~]# echo ${#a[@]} 25
列表赋值
1[root@castiel-Lu ~]# a[5]=6 2[root@castiel-Lu ~]# echo ${a[@]} 31 2 3 4 5 6
参数值的修改
1[root@castiel-Lu ~]# a[3]=0 2[root@castiel-Lu ~]# echo ${a[@]} 31 2 3 0 5 6
元素的删除
1// 删除列表内的值 2[root@castiel-Lu ~]# unset a[5] 3[root@castiel-Lu ~]# echo ${a[@]} 41 2 3 0 5 5// 删除数组 6[root@castiel-Lu ~]# unset a 7[root@castiel-Lu ~]# echo ${a[@]} 8
数组的分片
1[root@castiel-Lu ~]# a=(`seq 1 5`) 2[root@castiel-Lu ~]# echo ${a[@]} 31 2 3 4 5 4 5// 第一个数表示从哪个下标开始 6// 第二个数表示截取的个数 7// 例如这里表示从第3个值开始,截取2个数 8[root@castiel-Lu ~]# echo ${a[@]:2:2} 93 4 10 11// 这里0-1表示从倒数第2个值开始,往后截2个,但是目前只有一个5,所以显示了5 12// 从倒数第3个值开始,往后截2个,就能得到4和5 13[root@castiel-Lu ~]# echo ${a[@]:0-1:2} 145 15[root@castiel-Lu ~]# echo ${a[@]:0-2:2} 164 5 17
数组的替换
1[root@castiel-Lu ~]# echo ${a[@]/3/10} 21 2 10 4 5 3 4// ${a[@]/3/10}返回的是一串数字,所以赋值给a时需要加上()! 5[root@castiel-Lu ~]# a=(${a[@]/3/10}) 6[root@castiel-Lu ~]# echo ${a[@]} 71 2 10 4 5 8