1. 程式人生 > >Shell程式設計入門四:函式

Shell程式設計入門四:函式

使用者可以用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