Defining ranges in bash for loops didn't work

2019-08-13 06:57发布

问题:

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)