How to use looping in Linux bash script

Jephe Wu - http://linuxtechres.blogspot.com


Objective: list all kinds of Linux bash looping script which is useful for bash programming.
let computer do work for you.

Concept: 
Very often, we just need to run some script by loop to finish work


Examples


1. infinite loop

while true;do ...done
while [ 1 ]; do...done
while : ; do ....done

watch ls -l /tmp/file

2.  List a range of number 

list each line of /etc/hosts file
while read line;do echo $line;done < /etc/hosts

list number 1 to 10
for i in {1..10};do echo $i;done
for i in $(seq 1 10);do echo $i;done
for i in `seq 1 10`;do echo $i;done

list number 1 to 10 with same width
for i in {01..10};do echo $i;done
for i in $(seq -w 1 10);do echo $i;done
for i in `seq -w 1 10`;do echo $i;done

list number 1 to 10 with only odd number
for i in {1..10..2};do echo $i;done

list number 1 to 10 with only even number
for i in {2..10..2};do echo $i;done

Use just echo to list 1 to 10
echo {1..10}
echo {01..10}

Use just echo to list a-z and A-Z
echo {a..z}
echo {A..Z}

tranditional method to list 1 to 10
i=1;while [ $i -le 10 ];do echo $i;i=$[$i+1];done

i=1;while (( $i < 11 )); do echo $i; let i++; done
for (( i=0 ; i < 11 ; i++ )) ; do  echo $i ; done


3. Examples
Use loop to touch file a.txt, b.txt until z.txt?
for i in {a..z};do touch $i.txt;done