天天看点

shell中的函数 shell中的数组 告警系统需求分析

一、shell中的函数

[root@linux-01 aming]# cd /root/shell/aming

[root@linux-01 aming]# vim fun1.sh //需要注意函数名不能跟shell中的一些关键字冲突

#!/bin/bash

function inp(){

echo $1 $2 $3 $0 $#

}

inp 1 a 2

[root@linux-01 aming]# sh fun1.sh

1 a 2 fun1.sh 3 //$0是脚本名称、3是参数个数

继续改良脚本:

[root@linux-01 aming]# vim fun1.sh

echo "The first par is $1"

echo "The second par is $2"

echo "The third par is $3"

echo "the scritp name is $0"

echo "the number of par is $#"

inp b a 2 3 adf

[root@linux-01 aming]# sh fun1.sh //执行脚本

The first par is b

The second par is a

The third par is 2

the scritp name is fun1.sh

the number of par is 5

修改脚本:

inp $1 $2 $3

[root@linux-01 aming]# sh fun1.sh 1 //假如这里写一个参数,查看运行结果

The first par is 1

The second par is

The third par is

the number of par is 1

shell中的函数 shell中的数组 告警系统需求分析

定义一个加法的函数,shell中定义的函数必须放到上面

[root@linux-01 aming]# vim fun2.sh

sum() {

s=$[$1+$2] //s是一个变量,s=$1+$2

echo $s

sum 1 10 //求和1+10

[root@linux-01 aming]# sh fun2.sh //执行脚本

11

[root@linux-01 aming]# sh -x fun2.sh

  • sum 1 10
  • s=11
  • echo 11
    shell中的函数 shell中的数组 告警系统需求分析

    这个函数是专门用来显示IP的

    [root@linux-01 aming]# vim fun3.sh

    ip()

    {

    ifconfig |grep -A1 "$1: "|awk '/inet/ {print $2}'

read -p "Please input the eth name: " eth

ip $eth

[root@linux-01 aming]# sh -x fun3.sh //执行脚本

  • read -p 'Please input the eth name: ' eth

    Please input the eth name: ens33:0 //输入$1参数

  • ip ens33:0
  • ifconfig
  • grep -A1 'ens33:0: '
  • awk '/inet/ {print $2}'

    192.168.238.150 //得到ens33:0网卡的IP

改进脚本:需要判断输入的网卡是不是系统中的网卡,如果网卡存在,IP不存在,如何判断

我们现在的需求是看ens33这块网卡的IP信息:

[root@linux-01 aming]# ifconfig |grep -A1 "ens33" //-A1表示显示关键词,包括下面的一行,但是它看到的是两块网卡的信息,包括了虚拟网卡信息,继续让它只显示ens33网卡IP

ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500

inet 192.168.238.128 netmask 255.255.255.0 broadcast 192.168.238.255

ens33:0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500

inet 192.168.238.150 netmask 255.255.255.0 broadcast 192.168.238.255

[root@linux-01 aming]# ifconfig |grep -A1 "ens33: " //可以找到两块网卡名称不一样的地方

You have new mail in /var/spool/mail/root

[root@linux-01 aming]# ifconfig |grep -A1 "ens33: "|grep 'inet' //过滤出来inet这一行

[root@linux-01 aming]# ifconfig |grep -A1 "ens33: "|awk '/inet/ {print $2}' //使用这个命令过滤IP

192.168.238.128

[root@linux-01 aming]# ifconfig |grep -A1 "ens33: "|grep 'inet' |awk '{print $2}' //两个命令都可以

写shell脚本需要不断的去调试,不断的去寻求结果,达到预设,学习shell脚本一定要多练习,