Bash for loops are very useful in everyday life. I am going to post some simple examples where I combine bash for loops with other simple techniques like bash stepping etc.

Want to count from 1 – 100 and list each number sequentially?

for i in {1..100}; do   echo $i; done

Same as above but add a timestamp?

for i in {1..100}; do   echo $(date +"%D %I:%M:%S") - $i; done

Again same as above but now we step every 3 numbers instead of every 1

for i in {1..3..100}; do   echo $(date +"%D %I:%M:%S") - $i; done

 

now for something slightly harder, we add each successful result to the next number after it.

for i in {1..100}; do s=$((s+i)); done; echo $(date +"%D %I:%M:%S") - Total - $s

How about if we echo every resultant number before the total?

for i in {1..100}; do s=$((s+i)); echo $(date +"%D %I:%M:%S") - $s; done; echo $(date +"%D %I:%M:%S") - Total - $s

 

Leave a comment

Leave a Reply or the kitten gets it!