Sunday 23 March 2014

BASH LOOPS


Loop is to repeat some code continuously and exit based on the some expression evaluation.

FOR LOOP

basic for loop struct:
for statement
do
       commands block
done

there are quite a few common examples

  • for variable in 1 2 3 4 5
  • for variable in {1..5}
  • for i in $(seq 1 2 100)
  • for day in Monday Tuesday Wednesday Thursday Friday Saturday Sunday
  • for argument in "$*"
  • for(( integer = 1; integer <= 5; integer++ ))
  • for(( a=1, b=5; a <= 5; a++, b-- ))


WHILE LOOP

while expression
do
       commands block
done
the statement will be evaluated if true then will do the block, and re-evaluate the expression. The loop will exit untile the expression is false.
unitl loop is quite similar but until will always execute the loop at least once then evaluate the expression

break exit the loop
continue ignore the left loop block and continue an new loop

SELECT LOOP

select is very similar to the case statement in bash, it provides an interactive user interface.
Here is the sample code for user to select from a specified list

echo "What is your favorite color? "

select color in "red" "blue" "green" "white" "black"
do
    if [ $color ] ; then
              echo "You have selected $color"
              break
       else
              echo "Invalid selection"
       fi
done

it will ask the user to key in a
such as
what is your favorite color?
1)      red
2)      blue
3)      green
4)      white
5)      black
#? Red
Invalid selection
#? 0
Invalid selection
#? 1

You have selected red


No comments:

Post a Comment