While For Loops

Problem

You want to loop around a number of times and perform an action.



Solution

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



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...

Similarly 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



Reference

[tags], Unix Coding School[/tags]



Leave a Reply

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