天天看點

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腳本一定要多練習,