一个Shell编程方面的问题(关于传递参数的调用)

0 views
Skip to first unread message

吴雨龙

unread,
Jul 19, 2008, 7:46:31 AM7/19/08
to Linuxer家园
在Shell编程的学习过程中遇到了一个小问题,如下:
问:怎样在函数中用变量代替参数的位置的表述

想在函数中用变量代替参数的位置的表述,实现如下:
定义fred.sh文件内容如下:
#!/bin/sh
fred()
{
for i in 1 2 3
do
echo "the $i parameter is $$i"
done
return 0
}
fred $@

但是此文件在执行时显示:
the 1 parameter is 5999i
the 2 parameter is 5999i
the 3 parameter is 5999i

主要问题在于 $$i部分!

吴雨龙

unread,
Jul 20, 2008, 12:25:37 AM7/20/08
to Linuxer家园
我们自己想出了解决方案,正确程序如下:
#!/bin/sh
fred()
{
for i in 1 2 3
do
eval i='$'$i
echo "the i parameter is $i"
done
return 0}

fred $@

如果大家还有什么更好的办法,可以写出来,大家共同讨论。

李磊

unread,
Jul 20, 2008, 1:17:34 AM7/20/08
to linuxe...@googlegroups.com
2008/7/19 吴雨龙 <WYlon...@gmail.com>:
$$代表进程号。
用转译字符 \$$
>
> >
>

吴雨龙

unread,
Jul 24, 2008, 4:00:35 AM7/24/08
to linuxe...@googlegroups.com


2008/7/20 李磊 <lile...@gmail.com>:
>
> >
>
似乎不行啊。这样好像还是达不到目的啊,请明示。:)


李磊

unread,
Jul 24, 2008, 4:30:25 AM7/24/08
to linuxe...@googlegroups.com, xiyou...@googlegroups.com
2008/7/24 吴雨龙 <wylon...@gmail.com>:
这样的确不可以。sorry。
>> >
>> > >
>> >
>> 似乎不行啊。这样好像还是达不到目的啊,请明示。:)

#!/bin/sh
fred()
{
for i in 1 2 3
do
echo "the $i parameter is $1"
shift

done
return 0
}
fred $@
这样可以实现你所想要的功能。
我的理解是,传递参数,如果想调用参数,则必须用$(int)指明。
Reply all
Reply to author
Forward
0 new messages