Saturday, December 20, 2008

Ways of writing bash for loop


This might help the bash scripting newbies.

Here are some different ways of writing for loop in bash. The below one liners are just to show the loop iteration, does nothing significant !

way1:
$ for((i=1;i<=16;i+=2)); do echo $i; done

way2: jot is a command to print sequential or random data
$ for i in $(jot - 1 16 2); do echo $i; done

way3: seq prints sequential numbers
$ for i in $(seq 1 2 16); do echo $i; done

or

$ for i in `seq 1 2 16`; do echo $i; done

way4: Or if you want to explicitly write the for loop argumnets.
$ for i in 1 3 5 7 9 11 13 15; do echo $i; done

Related post:

- bash seq command explained
- bash jot command - print random or sequential data

2 comments:

А.Р. said...

Thanks,
for i in $(jot - 1 16 2); do echo $i; done

works nice even with non integer increments.

Unknown said...

Thanks

© Jadu Saikia www.UNIXCL.com