While For Loops

[problem]

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

[/problem]

[solution]

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

[/solution]

[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

[/example]

[reference]

[tags], Unix Coding School[/tags]

[/reference]

If you have found my website useful, please consider buying me a coffee below 😉

Leave a Reply

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