Chinaunix首页 | 论坛 | 博客
  • 博客访问: 113430
  • 博文数量: 27
  • 博客积分: 147
  • 博客等级: 入伍新兵
  • 技术积分: 175
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-20 09:03
文章分类

全部博文(27)

文章存档

2013年(1)

2012年(26)

我的朋友

分类:

2012-05-29 22:52:39

原文地址:shell函数参数 作者:ranson_zop

func()
{
echo $a $b $c
echo $1 $2 $3
echo "the end"
}
a="aaa"
b="bbb"
c="ccc"
func $a e f
echo "last"
echo $1

./example w c wc
运行结果:

aaa bbb ccc
aaa e f
the end
last
w

-------------i'm spliter------------------
execPrint()
{
    echo $@
    echo "1th arg:$1"
    echo "2th arg:$2"
}

#脚本自身的参数
echo $1

str="helloA helloB"
execPrint $str $1
execPrint "$str" $1

str="helloD"
execPrint $1 $str


./examplelist helloC
运行结果:
helloC
helloA helloB helloC
1th arg:helloA
2th arg:helloB
helloA helloB helloC
1th arg:helloA helloB
2th arg:helloC
helloC helloD
1th arg:helloC
2th arg:helloD
当一个函数被调用时,脚本程序的位置参数$*、$@、$#、$1、$2等会被替换为函数的参数。这也是你读取传递给函数的参数的办法。当函数执行完毕后,这些参数会恢复为它们先前的值。
Shell脚本与函数间的参数传递可利用位置参数和变量直接传递。变量的值可以由Shell脚本传递给被调用的函数,而函数中所用的位置参数$1、$2,等对应于函数调用语句中的实参,这一点是与普通命令不同的。

可以使用local关键字在shell函数中声明局部变量,局部变量将局限在函数的作用范围内。
脚本外也可以使用函数内变量,但必须执行过函数.
此外,函数可以访问全局作用范围内的其他shell变量。如果一个局部变量和一个全局变量的名字相同,前者就会覆盖后者,但仅限于函数的作用范围之内。


阅读(898) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~