在Shell中,調用函數時可以向其傳遞參數。在函數體內部,通過 $n 的形式來獲取參數的值,例如,$1表示第一個參數,$2表示第二個參數...
帶參數的函數示例:
- #!/bin/bash
- funWithParam(){
- echo "The value of the first parameter is $1 !"
- echo "The value of the second parameter is $2 !"
- echo "The value of the tenth parameter is $10 !"
- echo "The value of the tenth parameter is ${10} !"
- echo "The value of the eleventh parameter is ${11} !"
- echo "The amount of the parameters is $# !" # 參數個數
- echo "The string of the parameters is $* !" # 傳遞給函數的所有參數
- }
- funWithParam 1 2 3 4 5 6 7 8 9 34 73
運行腳本:
The value of the first parameter is 1 ! The value of the second parameter is 2 ! The value of the tenth parameter is 10 ! The value of the tenth parameter is 34 ! The value of the eleventh parameter is 73 ! The amount of the parameters is 12 ! The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"
注意,$10 不能獲取第十個參數,獲取第十個參數需要${10}。當n>=10時,需要使用${n}來獲取參數。
另外,還有幾個特殊變量用來處理參數,前面已經提到:
特殊變量 | 說明 |
---|---|
$# | 傳遞給函數的參數個數。 |
$* | 顯示所有傳遞給函數的參數。 |
$@ | 與$*相同,但是略有區別,請查看Shell特殊變量。 |
$? | 函數的返回值。 |