User Tools

Site Tools


howtos:bash_loop_examples
no way to compare when less than two revisions

Differences

This shows you the differences between two versions of the page.


howtos:bash_loop_examples [02/12/2018 21:34] (current) – created - external edit 127.0.0.1
Line 1: Line 1:
 +====== For sample ======
 +<code>
  
 +#!/bin/bash
 +for i in $( ls ); do
 +  echo item: $i
 +done
 +</code>
 +        
 +
 +====== C-like for ======
 +<code>
 +
 +#!/bin/bash
 +for i in `seq 1 10`;
 +do
 +  echo $i
 +done    
 +
 +</code>
 +        
 +====== While sample ======
 +
 +<code>
 +#!/bin/bash 
 +COUNTER=0
 +while [  $COUNTER -lt 10 ]; do
 +  echo The counter is $COUNTER
 +  let COUNTER=COUNTER+1 
 +done
 +
 +</code>
 +         
 +<code>
 +
 +#!/bin/bash
 +
 +var0=0
 +LIMIT=10
 +
 +while [ "$var0" -lt "$LIMIT" ]
 +#      ^                    ^
 +# Spaces, because these are "test-brackets" . . .
 +do
 +  echo -n "$var0 "        # -n suppresses newline.
 +  #                       Space, to separate printed out numbers.
 +
 +  var0=`expr $var0 + 1`   # var0=$(($var0+1))  also works.
 +                          # var0=$((var0 + 1)) also works.
 +                          # let "var0 += 1"    also works.
 +done                      # Various other methods also work.
 +
 +echo
 +
 +exit 0
 +</code>
 +
 +<code>
 +#!/bin/bash
 +
 +echo
 +                               # Equivalent to:
 +while [ "$var1" != "end" ]     # while test "$var1" != "end"
 +do
 +  echo "Input variable #1 (end to exit) "
 +  read var1                    # Not 'read $var1' (why?).
 +  echo "variable #1 = $var1"   # Need quotes because of "#" . . .
 +  # If input is 'end', echoes it here.
 +  # Does not test for termination condition until top of loop.
 +  echo
 +done  
 +
 +exit 0
 +
 +</code>
 +
 +Inside its test brackets, a while loop can call a function:
 +<code>
 +
 +t=0
 +
 +condition ()
 +{
 +  ((t++))
 +
 +  if [ $t -lt 5 ]
 +  then
 +    return 0  # true
 +  else
 +    return 1  # false
 +  fi
 +}
 +
 +while condition
 +#     ^^^^^^^^^
 +#     Function call -- four loop iterations.
 +do
 +  echo "Still going: t = $t"
 +done
 +
 +# Still going: t = 1
 +# Still going: t = 2
 +# Still going: t = 3
 +# Still going: t = 4
 +</code>
 +
 +====== Until sample ======
 +
 +<code>
 +#!/bin/bash 
 +COUNTER=20
 +until [  $COUNTER -lt 10 ]; do
 +  echo COUNTER $COUNTER
 +  let COUNTER-=1
 +done
 +         
 +</code>
 +
 +====== Snow in Terminal ======
 +<code>
 +while true
 +  do 
 +  N=$(($RANDOM % $COLUMNS))
 +  for i in $( seq 1 $N )
 +    do 
 +    echo -n " "
 +    done
 +    echo \*
 +  done
 +</code>
 +
 +And as a one-liner: 
 +<code>while true;do N=$(($RANDOM % $COLUMNS));for i in $( seq 1 $N );do echo -n " ";done;echo \*;done</code>
 +----
 +Source: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html
howtos/bash_loop_examples.txt · Last modified: 02/12/2018 21:34 by 127.0.0.1