在 bash 脚本中传入 for 循环的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4764383/
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
Arguments passed into for loop in bash script
提问by Milo Wielondek
I am trying to pass the argument as max limit for the for loop like this:
我试图将参数作为 for 循环的最大限制传递,如下所示:
#!/bin/bash
for i in {1..}
do
echo $i
done
This however returns {1..2}
when called with argument 2
, instead of executing the script and giving me
然而,这{1..2}
在使用参数调用时返回2
,而不是执行脚本并给我
1
2
回答by John Kugelman
Variable substitutions are not done inside of curly braces. You can use fixed numbers but not variables.
变量替换不在花括号内完成。您可以使用固定数字,但不能使用变量。
Brace Expansion
A sequence expression takes the form {x..y}, where x and y are either integers or single characters. ...
Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.
A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence expression. Any incorrectly formed brace expansion is left unchanged.
支撑扩展
序列表达式采用 {x..y} 形式,其中 x 和 y 是整数或单个字符。...
大括号扩展在任何其他扩展之前执行,并且任何其他扩展所特有的字符都保留在结果中。它是严格的文本。Bash 不对扩展的上下文或大括号之间的文本应用任何句法解释。
格式正确的大括号扩展必须包含不带引号的左括号和右括号,以及至少一个不带引号的逗号或有效的序列表达式。任何格式不正确的大括号扩展都保持不变。
Try one of these alternatives:
尝试以下替代方法之一:
for ((i = 1; i <= ; i++)); do
echo $i
done
# Not recommended with large sequences.
for i in $(seq 1 ); do
echo $i
done
回答by Daniel K
This will cycle through all true arguments (a.k.a. "testo mesto" is one argument)
这将遍历所有真实的论点(又名“testo mesto”是一个论点)
#cycle through all args
for (( i=1; i<=; i++ )); do
eval arg=$$i
echo "$arg"
done
OR
或者
#cycle through all args
for (( i=1; i<=; i++ )); do
echo "${!i}"
done
回答by Lasse
...or in the unlikely event that you really just want sequential numbers:
...或者万一您真的只想要序列号:
seq
:-)
:-)
回答by Jonathan Leffler
As well as John Kugelman's solution, you can use eval
like this:
除了 John Kugelman 的解决方案,您还可以这样使用eval
:
x=10; for i in $(eval echo {1..$x}); do echo $i; done
Or, if $1 is 10, then:
或者,如果 $1 是 10,则:
set -- 10
for i in $(eval echo {1..})
do
echo $i
done
You could also use some variants on:
您还可以在以下方面使用一些变体:
set -- 1000
eval echo {1..} |
while read i
do
echo $i
done
Or:
或者:
set -- 1000
while read i
do
echo $i
done <(eval echo {1..})
That uses process substitution.
这使用过程替换。