shell 自定义函数

函数就是把一小段代码整理到了一个小单元中,并给这个小单元起一个名字,当用到这段代码时直接调用这个小单元的名字即可.

格式:

函数语法中,前面的funcation 表示声明一个函数!!!

function 函数名 () {  

        指令...  
}

实例1:

#!/bin/bash

function color_echo()
{
  printf "\e[%dm%s\e[0m \n" $1 "$2"
}

function check_net()
{
        internet_domain="
        local.test.com:80
        local.test.com:443
        login.test.com:8080
        auth.test.com:8090
        "
        for domain in $internet_domain
        do
                #echo $domain
                color_echo  31  "connect to $domain fail"
        done
}

check_net

解析:先自定义一个color_echo函数,用于定义函数的颜色信息,再定义一个check_net函数,并循环函数中定义的域名和端口列表,最后调用并打印出来.

实例2:

#!/bin/bash

function color_echo()
{
        printf "\e[%dm %s\e[0m \n" $1 "$2"
}

function check_net()
{
        internet_domain="
        local.test.com:80
        local.test.com:443
        login.test.com:8080
        auth.test.com:8090
        "
        logicsvr_domain="
        192.168.1.1:80
        192.168.1.100:8080
        "

        for domain in $internet_domain $logicsvr_domain
        do
                res=`timeout 1 curl -Iv $domain 2>&1|grep -i connected`
                if [ "x$res" == "x" ]
                then
                        color_echo  31  "connect to $domain fail"
                else
                        echo "connect to $domain ok"
                fi
                #echo $domain
        done
}

check_net

解析:定义两个函数,在check_net函数中定义两个ip和url的组,并循环打印出来,然后进行访问,根据访问的结果输出成功和失败.

 2.获取主机ip地址实例:

get_lan_ip  () {
   #
   ip addr | grep -A5 -E ' enp0s3:' | \
       awk -F'[ /]+' '/inet/{
               split($3, N, ".")
               if ($3 ~ /^192.168/) {
                   print $3
               }
               if (($3 ~ /^172/) && (N[2] >= 16) && (N[2] <= 31)) {
                   print $3
               }
               if ($3 ~ /^10\./) {
                   print $3
               }
          }'

   return $?
}


get_lan_ip

 

参考文档:

    https://www.runoob.com/linux/linux-shell-func.html

 

posted @ 2019-07-02 14:11  梦徒  阅读(2862)  评论(0编辑  收藏  举报