如何使用变量在for循环一个bash [英] How to use variables in a bash for loop

查看:543
本文介绍了如何使用变量在for循环一个bash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个人如何在for循环是bash使用一个变量?
如果我只是用循环标准,它做什么,我希望

How does one use a variable in a bash for loop? If I just use a standard for loop, it does what I expect

for i in {0..3}
do
   echo "do some stuff $i"
done

这工作正常。它循环直通4次,0至3包容性,打印我的消息,并把数结尾。

This works fine. It loops thru 4 times, 0 to 3 inclusive, printing my message and putting the count at the end.

do some stuff 0
do some stuff 1
do some stuff 2
do some stuff 3

当我尝试使用以下for循环,同样的事情,似乎等于一个字符串,这是不是我想要的。

When I try the same thing with the following for loop, it seems to equal a string, which is not what i want.

length=3
for i in {0..$length}
do
   echo "do something right $i"
done

输出:

do something right {0..3}

我试过

for i in {0.."$length"} and for i in {0..${length}} (both output was {0..3})

for i in {0..'$length'} (output was {0..$length})

和他们都没有做什么,我需要。希望有人能帮助我。感谢您事先的任何bash的专家与循环帮助。

and they both don't do what I need. Hopefully someone can help me. Thanks in advance for any bash expert's help with for loops.

推荐答案

一种方法是使用评估

for i in $( eval echo {0..$length} )
do
       echo "do something right $i"
done

注意的,当你设置时会发生什么长度=; LS 长度=; RM * (不要试图后者虽然)。

Note what happens when you set length=;ls or length=; rm * (don't try the latter though).

安全的,使用 SEQ

for i in $( seq 0 $length )
do
       echo "do something right $i"
done

,也可以使用C风格的for循环,这也是安全的:

or you can use the c-style for loop, which is also safe:

for (( i = 0; i <= $length; i++ )) 
do 
       echo "do something right $i"
done

这篇关于如何使用变量在for循环一个bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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