函數就是把一小段代碼整理到了一個小單元中,並給這個小單元起一個名字,當用到這段代碼時直接調用這個小單元的名字即可.
格式:
函數語法中,前面的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