Looping with For and While

Problem

You want to loop a number of times in UNIX.



Solution

Being able to loop around a given number of times, fully utilizes the power of UNIX. See the examples.



Example


For example, spin around 100 times and print hello:

i=0; while [[ $i -lt 100 ]] ; do echo -n 'hello'; ((i++)) ; done; echo ''
hellohellohellohellohellohellohellohellohellohello
hellohellohellohellohellohellohellohellohellohello
hellohellohellohellohellohellohellohellohellohello
hellohellohellohellohellohellohellohello...

Similarily the for command is a beauty too, spin around 5 times and kick off a loop 5 times – paste the result into 5 columns:


for i in 1 2 3 4 5; do for j in 1 2 3 4 5; do echo "$i:$j"; done; done | paste - - - - -
1:1 1:2 1:3 1:4 1:5
2:1 2:2 2:3 2:4 2:5
3:1 3:2 3:3 3:4 3:5
4:1 4:2 4:3 4:4 4:5
5:1 5:2 5:3 5:4 5:5





Leave a Reply

Your email address will not be published. Required fields are marked *