BASH For Loops


BASH script under linux supports the for loops. There are quite a few ways to write for loops.

1. List the Values

for I in 1 2 3; do echo $I; done

2. Use ‘SEQ’ to list the values (but depreciated)

for I in $(seq 1 3); do echo $I; done # or seq(1 1 3)

3. C-style for in (( .. ))

for ((I=1; I <= 3 ; I++)); do echo $I; done

4. {..} to list the set

for I in {1..3}; do echo $I; done  #bashV4.0+, or {1..3..1}

All above print 1 2 3. You can use ‘continue’ or ‘break’ as like other languages to jump to next or out of the loop.

for i in {1..100}; do
   if [ $i -eq 50 ]; then break; fi
   if [ $i -eq 30 ]; then echo $i; continue; fi
done

gives the output of 30.

Happy scripting!

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
197 words
Last Post: Avoid Javascript whenever possible
Next Post: Running VBScript in MS ScriptControl

The Permanent URL is: BASH For Loops

Leave a Reply