pro bash programming学习笔记——第六章

本文详细介绍了Shell函数的定义方法、变量作用域及如何定义复合指令等内容。通过实例展示了如何使用Shell函数来验证IP地址的合法性及对整数进行排序。

Shell 函数


函数与调用它的脚本运行在同一进程中,所以它可以访问脚本里的所有变量

定义语法

在kornshell中,函数的定义方式为:
function name <compound command>
bourne shell中,函数的定义方式为:
name() <compound command>
这种定义方式后来也被包括在了ksh中,并且成为了POSIX的标准。

bash支持上述两种定义方法,还可以如下定义函数:
function name() <compound command>

函数以return结束,如果return后面有参数,则函数的退出状态就是这个参数,如果没有参数,则函数的退出状态就是其最后被执行的语句退出状态。

变量前面加上local关键字后,这个变量就只在函数内可见。local可以接选项-A表示定义的是一个组合数组。

下面这个函数可以用来检查一个串是否是合法ip地址
   isvalidip() #@ USAGE: isvalidip DOTTED-QUAD
   {
     case $1 in
       ## reject the following:
       ##   empty string
       ##   anything other than digits and dots
       ##   anything not ending in a digit
       "" | *[!0-9.]* | *[!0-9]) return 1 ;;
     esac
     ## Change IFS to a dot, but only in this function
     local IFS=.
  ## Place the IP address into the positional parameters;
  ## after word splitting each element becomes a parameter
  set -- $1
  [ $# -eq 4 ] && ## must be four parameters
                  ## each must be less than 256
  ## A default of 666 (which is invalid) is used if a parameter is empty
  ## All four parameters must pass the test
  [ ${1:-666} -le 255 ] && [ ${2:-666} -le 255 ] &&
  [ ${3:-666} -le 255 ] && [ ${4:-666} -le 255 ]
}

其中set -- $1命令就是把$1设定为函数的参数(以IFS分隔)。

复合指令

如果函数中只有一个语句,则,则可以不用大括号。如前几章举过的例子:
valint() #@ USAGE: valint INTEGER
  case ${1#-} in      ## Leading hyphen removed to accept negative numbers
    *[!0-9]*) false;; ## the string contains a non-digit character
    *) true ;;        ## the whole number, and nothing but the number
  esac

如果函数体以小括号括起来,则函数调用时会在子shell中执行。
如:
funky() ( name=nobody; echo "name = $name" )
name=Rumpelstiltskin
funky
输出会是:
name = nobody
name = Rumpelstiltskin

取得函数运行结果

可以在函数中return一个返回值,该值只能是0到255之间的整数。

可以通过printf指令输出一些结果。

还可以将结果放在变量中,如:

_max3() { #@ Sort 3 integers and store in $_MAX3, $_MID3 and $_MIN3
    [ $# -ne 3 ]  && return 5
    [ $1 -gt $2 ] && { set -- $2 $1 $3; }
    [ $2 -gt $3 ] && { set -- $1 $3 $2; }
    [ $1 -gt $2 ] && { set -- $2 $1 $3; }
    _MAX3=$3
    _MID3=$2
    _MIN3=$1
}

对输入的三个数进行排序。



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值