Shell编程入门四:函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/transformer_WSZ/article/details/79294738

用户可以用shell定义函数,然后子啊shell脚本中随便调用。shell中函数的定义格式如下:

[ function ] funname [()]
{
    action;
    [return int;]
}
  • 可以带 function fun() 定义,也可以直接 fun() 定义,不带任何参数。
  • 参数返回,可以显示加:return 返回,如果不加,将以最后一条命令运行结果,作为返回值。 return 后跟数值 n(0-255)

不含 return

demoFun(){
    echo "This is my first function"
}
echo "-----func start-----"
demoFun
echo "-----func end-----"

包含 return

funWithReturn(){
    echo "add action"
    echo "input first num: "
    read aNum
    echo "input second num: "
    read anotherNum
    echo "The two nums are $aNum and $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
echo "The total of two nums are $? "

函数返回值在调用该函数后通过 $? 来获得。

注意:所有函数在使用前必须定义。这意味着必须将函数放在脚本开始部分,直至shell解释器首次发现它时,才可以使用。调用函数仅使用其函数名即可。

函数参数

在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1 表示第一个参数,$2 表示第二个参数 ……

funWithParam(){
    echo "first : $1 "
    echo "second : $2 "
    echo "tenth : $10 "
    echo "tenth : ${10} "
    echo "eleventh : ${11} "
    echo "total num : $# "
    echo "the single string : $* "
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

注意:$10 不能获取第十个参数,获取第十个参数需要 ${10} 。当 n>=10 时,需要使用 ${n} 来获取参数。


参考自:http://www.runoob.com/linux/linux-shell-func.html

猜你喜欢

转载自blog.csdn.net/transformer_WSZ/article/details/79294738