User Tools

Site Tools


howtos:bash_loop_examples

For sample

#!/bin/bash
for i in $( ls ); do
  echo item: $i
done

C-like for

#!/bin/bash
for i in `seq 1 10`;
do
  echo $i
done    

While sample

#!/bin/bash 
COUNTER=0
while [  $COUNTER -lt 10 ]; do
  echo The counter is $COUNTER
  let COUNTER=COUNTER+1 
done
#!/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
#!/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

Inside its test brackets, a while loop can call a function:

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

Until sample

#!/bin/bash 
COUNTER=20
until [  $COUNTER -lt 10 ]; do
  echo COUNTER $COUNTER
  let COUNTER-=1
done
         

Snow in Terminal

while true
  do 
  N=$(($RANDOM % $COLUMNS))
  for i in $( seq 1 $N )
    do 
    echo -n " "
    done
    echo \*
  done

And as a one-liner:

while true;do N=$(($RANDOM % $COLUMNS));for i in $( seq 1 $N );do echo -n " ";done;echo \*;done

Source: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html

howtos/bash_loop_examples.txt · Last modified: 02/12/2018 20:34 by 127.0.0.1