co-worker
co-worker

Reputation: 213

How to loop in bash script?

i have following lines in a bash script under Linux:

...
mkdir max15
mkdir max14
mkdir max13
mkdir max12
mkdir max11
mkdir max10
...

how is the syntax for putting them in a loop, so that i don't have to write the numbers (15,14..) ?

Upvotes: 6

Views: 15896

Answers (5)

Chen Levy
Chen Levy

Reputation: 16338

No loop needed for this task:

mkdir max{15..10} max0{9..0}

... but if you need a loop construct, you can use one of:

for i in $(seq [ <start> [ <step> ]] <stop>) ; do
     # you can use $i here
done

or

for i in {<start>..<stop>} ; do 
     # you can use $i here
done

or

for (( i=<start> ; i < stop ; i++ )) ; do
     # you can use $i here
done

or

seq [ <start> [ <step> ]] <stop> | while read $i ; do
     # you can use $i here
done

Note that this last one will not keep the value of $i outside of the loop, due to the | that starts a sub-shell

Upvotes: 9

eumiro
eumiro

Reputation: 212825

for a in `seq 10 15`; do mkdir max${a}; done

seq will generate numbers from 10 to 15.

EDIT: I was used to this structure since many years. However, when I observed the other answers, it is true, that the {START..STOP} is much better. Now I have to get used to create directories this much nicer way: mkdir max{10..15}.

Upvotes: 5

ghostdog74
ghostdog74

Reputation: 342263

with bash, no need to use external commands like seq to generate numbers.

for i in {15..10}
do
 mkdir "max${i}"
done

or simply

mkdir max{01..15} #from 1 to 15

mkdir max{10..15} #from 10 to 15

say if your numbers are generated dynamically, you can use C style for loop

start=10
end=15
for((i=$start;i<=$end;i++))
do
  mkdir "max${i}"
done

Upvotes: 19

MOnsDaR
MOnsDaR

Reputation: 8654

Use a for-loop

Upvotes: 3

chrisaycock
chrisaycock

Reputation: 37930

for i in {1..15} ; do
    mkdir max$i
done

Upvotes: 1

Related Questions