参数传递到在bash脚本循环 [英] Arguments passed into for loop in bash script

查看:105
本文介绍了参数传递到在bash脚本循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图传递参数为最大限制为像这样的循环:

 #!/斌/庆典因为我在{1 .. $ 1}

    回声$我
DONE

然而,这将返回 时的说法叫做 2 的{} 1..2,而不是执行脚本和给我

  1
2


解决方案

变量替换并不大括号内完成。您可以使用固定电话号码,但不变量。


  

括号扩展


  
  

一个序列的前pression的形式为{x..y},其中x和y是任一整数或单个字符。 ...


  
  

括号扩展是在任何其他扩展之前进行的,特向其他扩展的任何字符都在结果pserved $ P $。这是严格的文本。巴什没有任何语法间pretation适用于扩展的上下文或花括号之间的文本。


  
  

一个正确形成括号扩展必须包含没有引用的开闭括号,以及至少一个没有引用的逗号或有效序列的前pression。任何格式不正确括号扩展将保持不变。


尝试这些替代选择之一:

 为((i = 1; I< = $ 1;我++));做
    回声$我
DONE#不推荐用大序列。
因为我在$(SEQ 1 $ 1);做
    回声$我
DONE

I am trying to pass the argument as max limit for the for loop like this:

#!/bin/bash

for i in {1..$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

解决方案

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.

Try one of these alternatives:

for ((i = 1; i <= $1; i++)); do
    echo $i
done

# Not recommended with large sequences.
for i in $(seq 1 $1); do
    echo $i
done

这篇关于参数传递到在bash脚本循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆