在 Shell中,調(diào)用函數(shù)時(shí)可以向其傳遞參數(shù)。在函數(shù)體內(nèi)部,通過 $n 的形式來獲取參數(shù)的值,例如,$1 表示第一個(gè)參數(shù),$2 表示第二個(gè)參數(shù)...
帶參數(shù)的函數(shù)示例:
#!/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 $# !" # 參數(shù)個(gè)數(shù)
echo "The string of the parameters is $* !" # 傳遞給函數(shù)的所有參數(shù)
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
運(yùn)行腳本:
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 不能獲取第十個(gè)參數(shù),獲取第十個(gè)參數(shù)需要 ${10}。當(dāng) n>=10 時(shí),需要使用 ${n} 來獲取參數(shù)。
另外,還有幾個(gè)特殊變量用來處理參數(shù),前面已經(jīng)提到:
特殊變量 | 說明 |
---|---|
$# | 傳遞給函數(shù)的參數(shù)個(gè)數(shù)。 |
$* | 顯示所有傳遞給函數(shù)的參數(shù)。 |
$@ | 與 $* 相同,但是略有區(qū)別,請查看 Shell 特殊變量。 |
$? | 函數(shù)的返回值。 |