把一段代码整理到了一个小单元中,并给这个小单元起一个名字,当用到这段代码时直接调用这个小单元的名字便可。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