在 bash for 循环中使用命令行参数范围打印包含参数的括号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5691098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using command line argument range in bash for loop prints brackets containing the arguments
提问by ru4mqart668op514
It's probably a lame question. But I am getting 3 arguments from command line [ bash script ]. Then I am trying to use these in a for loop.
这大概是个蹩脚的问题。但是我从命令行 [bash 脚本] 得到了 3 个参数。然后我试图在 for 循环中使用这些。
for i in {..}
do action1
done
This doesn't seem to work though and if $1
is "0"
and $2
is 2
it prints {0..2}' and calls
action1` only once. I referred to various examples and this appears to be the correct usage. Can someone please tell me what needs to be fixed here?
这似乎并没有工作时,虽然如果$1
是"0"
和$2
是2
它打印{0..2}' and calls
action1`只有一次。我参考了各种示例,这似乎是正确的用法。有人可以告诉我这里需要修复什么吗?
Thanks in advance.
提前致谢。
回答by Vijayender
You can slice the input using ${@:3}
or ${@:3:8}
and then loop over it
您可以使用${@:3}
or对输入进行切片${@:3:8}
,然后对其进行循环
For eg., to print arguments starting from 3
例如,打印从 3 开始的参数
for i in ${@:3} ; do echo $i; done
or to print 8 arguments starting from 3 (so, arguments 3 through 10)
或打印从 3 开始的 8 个参数(因此,参数 3 到 10)
for i in ${@:3:8} ; do echo $i; done
回答by zxt
How about:
怎么样:
for i in $(eval echo {..}); do echo $i; done
回答by kurumi
Use the $@ variable?
使用 $@ 变量?
for i in $@
do
echo $i
done
If you just want to use 1st and 2nd argument , just
如果您只想使用第一个和第二个参数,只需
for i in
If your $1 and $2 are integers and you want to create a range, use the C for loop syntax (bash)
如果您的 $1 和 $2 是整数并且您想创建一个范围,请使用 C for 循环语法 (bash)
for ((i=;i<=;i++))
do
...
done
回答by rthere
I had a similar problem. I think the issue is with dereferencing $1 within the braces '{}'. The following alternative worked for me ..
我有一个类似的问题。我认为问题在于在大括号“{}”中取消引用 $1。以下替代方案对我有用..
#!/bin/bash
for ((i=;i<=;i++))
do
...
done
Hope that helps.
希望有帮助。
回答by Rolf ?
#/bin/bash
for i
do
echo Value: $i
done
This will loop over all arguments given to the script file. Note, no "do" or anything else after the loop variable i.
这将循环给脚本文件的所有参数。注意,在循环变量 i 之后没有“do”或其他任何东西。