20.16/20.17 shell中的函数

shell中的函数

  • 把一段代码整理到了一个小单元中,并给这个小单元起一个名字,当用到这段代码时直接调用这个小单元的名字便可。shell

  • 函数就是一个子shell,就是一个代码段,定义完函数就能够引用它bash

  • 格式:函数

    • function 后是函数的名字,而且 function 这个单词是能够省略掉的
      • 花括号{} 里面为具体的命令
格式: function f_name() {
                      command
             }
函数必需要放在最前面
  • 示例1
    • 这个函数是用来打印参数
#!/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]#
  • 函数,能够直接写在脚本内,至关于直接调用
    • 內建变量
    • $1 第一个参数
    • $2 第二个参数
    • ...
    • ~
    • $# 参数名字
    • $0 总共有几个参数
[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]#

  • 示例2
    • 用于定义加法的函数,shell中定义的函数,必须放在上面
    • 在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]#

  • 示例3
    • 显示IP,输入网卡的名字,而后显示网卡的IP
#!/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"
  • grep -A1 "ens33" 过滤显示出关键词及关键词下的一行
[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
  • 案例4
    • 断定是否为本机的网卡,断定输入的网卡是否有IP
#!/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
相关文章
相关标签/搜索