查看: 1889|回复: 0
打印 上一主题 下一主题

Shell函数参数

[复制链接]
跳转到指定楼层
沙发
发表于 2014-8-18 10:43:16 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 lucky80204 于 2014-8-18 10:44 编辑

在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数...

带参数的函数示例:
  1. #!/bin/bash
  2. funWithParam(){
  3.     echo "The value of the first parameter is $1 !"
  4.     echo "The value of the second parameter is $2 !"
  5.     echo "The value of the tenth parameter is $10 !"
  6.     echo "The value of the tenth parameter is ${10} !"
  7.     echo "The value of the eleventh parameter is ${11} !"
  8.     echo "The amount of the parameters is $# !"  # 参数个数
  9.     echo "The string of the parameters is $* !"  # 传递给函数的所有参数
  10. }
  11. funWithParam 1 2 3 4 5 6 7 8 9 34 73
复制代码

运行脚本:
  1. The value of the first parameter is 1 !
  2. The value of the second parameter is 2 !
  3. The value of the tenth parameter is 10 !
  4. The value of the tenth parameter is 34 !
  5. The value of the eleventh parameter is 73 !
  6. The amount of the parameters is 12 !
  7. The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"
复制代码

注意,$10 不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数。

另外,还有几个特殊变量用来处理参数,前面已经提到:
特殊变量 说明
$# 传递给函数的参数个数。
$* 显示所有传递给函数的参数。
$@ 与$*相同,但是略有区别,请查看Shell特殊变量。
$? 函数的返回值。



回复

使用道具 举报

您需要登录后才可以回帖 登录 | 加入因仑

本版积分规则

快速回复 返回顶部 返回列表