Defining ranges in bash for loops didn't work

最后都变了- 提交于 2019-12-11 06:08:51

问题


I have the following for loop in bash that creates loop devices in a chrooted directory.

for var in 0 1 2 3 .. 7
do
    MAKEDEV -d ${CHROOT}/dev -x loop$var
done

This didn't work for me as after it creates loop3 it takes .. literally and tries to create loop.. and fails. However according to this tutorial it should have worked. I got it to work by doing the following:

for (( var=0; var<=7; var++ ))
do
    MAKEDEV -d ${CHROOT}/dev -x loop$var
done

I still want to know why the for loop I tried first didn't work. Please help.


回答1:


I think you are reading the tutorial too literally. The turorial does say

for VARIABLE in 1 2 3 4 5 .. N

but taken literally this is not correct bash syntax - I think the author is simply trying to say that for this kind of for loop you need to explicitly list out all values you need to iterate over. So in your case this would be:

for var in 0 1 2 3 4 5 6 7

The tutorial also mentions brace expansion, which @glennjackman gives in his answer which is also entirely correct syntax.




回答2:


In bash, you can write

for var in {0..7}

You cannot say

end=7
for var in {0..$end}

because brace expansion occurs before variable expansion. If you have your range points in variables, you can use a C-style for loop (as you did) or seq

for var in $(seq 0 $var)


来源:https://stackoverflow.com/questions/19057874/defining-ranges-in-bash-for-loops-didnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!