Shell 函數
shell函數定義
- 1、可以帶function fun() 定義,也可以直接fun() 定義,不帶任何參數。
- 2、參數返回,可以顯示加:return 返回,如果不加,將以最後一條命令運行結果,作爲返回值。 return後跟數值n(0-255)
函數參數
在Shell中,調用函數時可以向其傳遞參數。在函數體內部,通過 $n 的形式來獲取參數的值,例如,$1表示第一個參數,$2表示第二個參數... 注意,$10 不能獲取第十個參數,獲取第十個參數需要${10}。當n>=10時,需要使用${n}來獲取參數。
函數示例:
$ funWithParam()
{
echo "The first para $1 !"
echo "The second para $2 !"
echo "The tenth para $10 !"
echo "The tenth para ${10} !"
echo "The total para $# !"
echo "output as a string $* !"
echo `date`
}
#運行結果如下
$ funWithParam 1 2 3 4 5 6 7 8 9 55 66 77
The first para 1 !
The second para 2 !
The tenth para 10 !
The tenth para 55 !
The total para 12 !
output as a string 1 2 3 4 5 6 7 8 9 55 66 77 !
2018年10月10日 14:00:48