|
Shell编程:Linux系统环境程序设计之路
函数
别的高级语言都有函数的感念,当然shell编程也有这个概念,当写一个比较大型的shell程序的时候,如果没有函数,则会到处都是重复的代码。当然也可以调用别的脚本,但是速度会比较慢。所以函数是必不可少并且非常重要的一个东西。
定义函数的格式
function_name(){...}
例子:
//~ fun_s
show(){
echo "show $*"
}
echo $*
echo "after function"
show c d
echo $*
exit 0
/////////////////////////////
$./fun_s a b
结果是
a b
after function
c d
a b
从上面的例子可以看出,当脚本调用函数的时候,脚本程序的位置参数会被替换成函数的位置参数,并且函数调用结束后还原。
return:
//~ return_s
#!/bin/bash
first(){
echo "is return"
}
second(){
echo "before return"
return "0"
echo "after return"
}
return_value="$(first)"
echo $return_value
second&&echo "return 0"||echo "return other"
exit 0
//////////////////////////////////////
输出
is return
before return
return 0
该例子说明可以捕获函数内echo的字符串,如echo $(first) , 函数在return后不会再执行下面的语句。
second&&echo "return 0"||echo "return other" 该句的输出为 return 0。这里有人可能会和C语言混淆,因为在C语言里0表示的是false。而这里的0表示函数执行成功,可以理解为true,所以会输出return 0。
[1] [2] [3] 下一页 |