把一段代碼整理到了一個小單元中,並給這個小單元起一個名字,當用到這段代碼時直接調用這個小單元的名字便可。shell
函數就是一個子shell,就是一個代碼段,定義完函數就能夠引用它bash
格式:函數
格式: function f_name() { command } 函數必需要放在最前面
#!/bin/bash input() { echo $1 $2 $# $0 } input 1 a b
[root@hf-01 shell]# cat !$ cat function.sh #! /bim/bash function input(){ echo $1 $2 $# $0 } input 1 a b [root@hf-01 shell]# sh -x function.sh + input 1 a b + echo 1 a 3 function.sh 1 a 3 function.sh [root@hf-01 shell]# sh function.sh 1 a 3 function.sh [root@hf-01 shell]#
[root@hf-01 shell]# cat function.sh #! /bim/bash function input(){ echo $1 $2 $# $0 } input $1 $2 [root@hf-01 shell]# sh function.sh 1 4 1 4 2 function.sh [root@hf-01 shell]#
#!/bin/bash sum() { s=$[$1+$2] #定義變量s = $1+$2 /其中 $1爲第一個參數,$2爲第二個參數 echo $s } sum 1 2 #輸出 第一個參數和第二個參數
[root@hf-01 shell]# cat !$ cat fun2.sh #! /bin/bash sum(){ s=$[$1+$2] echo $s } sum 1 2 [root@hf-01 shell]# sh -x !$ sh -x fun2.sh + sum 1 2 + s=3 + echo 3 3 [root@hf-01 shell]#
#!/bin/bash ip() { ifconfig |grep -A1 "eno16777736: " |awk '/inet/ {print $2}' #查看網卡,過濾出ens33及下面的一行,匹配inet行並打印出第二段 } read -p "Please input the eth name: " e myip=`ip $e` echo "$e address is $myip"
[root@hf-01 shell]# ifconfig |grep -A1 "eno16777736" eno16777736: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.202.130 netmask 255.255.255.0 broadcast 192.168.202.255 -- eno16777736:0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.202.150 netmask 255.255.255.0 broadcast 192.168.202.255 [root@hf-01 shell]# ifconfig |grep -A1 "eno16777736" |tail -1 inet 192.168.202.150 netmask 255.255.255.0 broadcast 192.168.202.255
#!/bin/bash #coding:utf8 ip() { a=`ifconfig |grep -A1 "$1 " |tail -1 |awk -F" " '{print $2}'` if [ -z "$a" ] then echo $1 echo "沒有這個網卡名" exit 1 fi b=`echo $a |grep addr` if [ -z "$b" ] then echo $1 echo "此網卡沒有IP地址" exit 1 fi echo $a } read -p "請輸入你的網卡名字: " eth ip $eth