Shell函数参数
在Shell中,調(diào)用函數(shù)時可以向其傳遞參數(shù)。在函數(shù)體內(nèi)部,通過 $n 的形式來獲取參數(shù)的值,例如,$1表示第一個參數(shù),$2表示第二個參數(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ù)個數(shù) echo "The string of the parameters is $* !" # 傳遞給函數(shù)的所有參數(shù) } 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 不能獲取第十個參數(shù),獲取第十個參數(shù)需要${10}。當n>=10時,需要使用${n}來獲取參數(shù)。
另外,還有幾個特殊變量用來處理參數(shù),前面已經(jīng)提到:
帶參數(shù)的函數(shù)示例:
另外,還有幾個特殊變量用來處理參數(shù),前面已經(jīng)提到:
| $# | 傳遞給函數(shù)的參數(shù)個數(shù)。 |
| $* | 顯示所有傳遞給函數(shù)的參數(shù)。 |
| $@ | 與$*相同,但是略有區(qū)別,請查看Shell特殊變量。 |
| $? | 函數(shù)的返回值。 |
總結(jié)
- 上一篇: Shell函数:Shell函数返回值、删
- 下一篇: Shell输入输出重定向:Shell H