【Shell脚本学习23】Shell函数参数
2016-01-03 19:53
513 查看
在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
运行脚本:
注意,$10 不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数。
另外,还有几个特殊变量用来处理参数,前面已经提到:
带参数的函数示例:
#!/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特殊变量。 |
$? | 函数的返回值。 |
相关文章推荐
- 【Shell脚本学习22】Shell 函数:Shell函数返回值、删除函数、在终端调用函数
- 【Shell脚本学习21】Shell break和continue命令
- 【Shell脚本学习20】Shell until循环
- 【Shell脚本学习19】Shell while循环
- 【Shell脚本学习18】Shell for循环
- 【Shell脚本学习17】Shell case esac语句
- 【Shell脚本学习16】Shell if else语句
- 【Shell脚本学习15】shell printf命令:格式化输出语句
- 【Shell脚本学习14】Shell echo命令
- 【Shell脚本学习13】Shell数组:shell数组的定义、数组长度
- 【Shell脚本学习12】Shell字符串
- 【Shell脚本学习11】Shell注释
- 【Shell脚本学习10】Shell运算符:Shell算数运算符、关系运算符、布尔运算符、字符串运算符等
- 【Shell脚本学习9】Shell替换:Shell变量替换,命令替换,转义字符
- 【Shell脚本学习8】Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数
- 【Shell脚本学习7】Shell脚本学习指南分享
- 【Shell脚本学习6】Shell变量:Shell变量的定义、删除变量、只读变量、变量类型
- 【Shell脚本学习5】第一个Shell脚本
- 【Shell脚本学习4】几种常见的Shell
- 【Shell脚本学习3】什么时候使用Shell