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
}
对输入的三个数进行排序。
本文详细介绍了Shell函数的定义方法、变量作用域及如何定义复合指令等内容。通过实例展示了如何使用Shell函数来验证IP地址的合法性及对整数进行排序。
5万+

被折叠的 条评论
为什么被折叠?



