bash for 循环中的命令行替换
我有一个测试脚本 test.sh,我试图将命令行参数打印到脚本中,但以下内容无法按预期工作
`#!/bin/bash
for((i=1;i<"$#";i++)) do
printf "Position %s of argumentArray has %s \n", $i $(($i))
done`
(我的想法是 (()) 将进行数学评估,结果为 $1 $2 等。)运行时两者都没有
for((i=1;i<"$#";i++)) do
printf "Position %s of argumentArray has %s \n", $i $"$( eval echo $i )"
done
给出输出,如下所示,
./test.sh first second third
Position 1 of argumentArray has 1
Position 1 of argumentArray has 2
Position 1 of argumentArray has 3
而不是
Position 1 of argumentArray has first
Position 1 of argumentArray has second
Position 1 of argumentArray has third
我面临同样的问题,
for((i=1;i<="$#";i++))
do
case "$($i)" in
.......
案例评估为 1 ,2 3 等插入实际参数传递。
请帮助我理解我哪里出错了。
I have a test script test.sh where I am trying to print out command line arguments.to the script but the following does not work as expected
`#!/bin/bash
for((i=1;i<"$#";i++)) do
printf "Position %s of argumentArray has %s \n", $i $(($i))
done`
( my idea was that the (()) will do the mathematical evaluation resulting in $1 $2 etc.) Neither does
for((i=1;i<"$#";i++)) do
printf "Position %s of argumentArray has %s \n", $i $"$( eval echo $i )"
done
both gives as out put when run as follows
./test.sh first second third
Position 1 of argumentArray has 1
Position 1 of argumentArray has 2
Position 1 of argumentArray has 3
instead of
Position 1 of argumentArray has first
Position 1 of argumentArray has second
Position 1 of argumentArray has third
I face the same problem with
for((i=1;i<="$#";i++))
do
case "$($i)" in
.......
case evaluates to 1 ,2 3 etc insted of the actual parameter passed in.
Please help me in understanding where I am going wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用间接扩展来公平地做到这一点很容易:
我还修复了上面的一些小问题:循环结束条件应该是
i<=$#
来打印最后一个参数,printf
,然后应该用双引号将参数 ("${!i}"
) 括起来,以防它有任何空格或其他有趣的字符。You can use indirect expansion to do this fairly easily:
I also fixed some minor problems in the above: the loop end condition should be
i<=$#
to print the last arg, there shouldn't be a comma after the format string forprintf
, and there should be double-quotes around the argument ("${!i}"
) in case it has any spaces or other funny characters.命令行参数可以直接访问,但是如果您想按位置访问它们,您可以这样做:
运行脚本:
ADDENDUM
有关 Bash 数组的信息:
The commandline arguments can be accessed directly but if you want them by position you can do this:
A run of the script:
ADDENDUM
Information on Bash arrays: