licão 12 decision loops - statement iteration

34
Lesson 12 Decision with Loops Statement Iteration While Until For Select Nesting loops Loop Control Infinite Break Continue

Upload: acacio-oliveira

Post on 13-Jul-2015

69 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Licão 12 decision loops - statement iteration

Lesson 12• Decision with Loops

• Statement Iteration

• While

• Until

• For

• Select

• Nesting loops

• Loop Control

• Infinite

• Break

• Continue

Page 2: Licão 12 decision loops - statement iteration

Decision Making with loopsIteration Statements

LoopsPowerful programming tool that enables execution of a set of commands repeatedly.

• The while loop

• The for loop

• The until loop

• The select loop

Nesting LoopsAll loops support nesting

– You can put one loop inside another similar or different loops.This nesting can go up to unlimited number of times based on your requirement.

Page 3: Licão 12 decision loops - statement iteration

while loop

while loop iterates “while” the expression is true

enables to execute a set of commands repeatedly until some condition occurs. It is usually used to manipulate the value of a variable repeatedly.

• It’s a looping structure. Executes a set of commands while a specified condition is true. • The loop terminates as soon as the condition becomes false. • If condition never becomes false, loop will never exit.

Syntax:

while commanddoStatement(s) to be executed if command is true done

• If the resulting value is true, given statement(s) are executed.

• If command is false then no statement would be not executed and program would jump to the next line after done statement.

Page 4: Licão 12 decision loops - statement iteration

while loop

#!/bin/sha=0 while [ $a -lt 10 ] do echo $a a=`expr $a + 1` done

example display the numbers zero to nine

0 1 2 3 4 5 6 7 8 9

example result

• Each time this loop executes, the variable a is checked to seewhether it has a value that is less than 10.

• If the value of a is less than 10, this test condition has an exitstatus of 0.

• In this case, current value of a is displayed, then a is incrementedby 1.

Page 5: Licão 12 decision loops - statement iteration

while loop

#!/bin/bashCOUNTER=0while [ $COUNTER -lt 10 ]; dolet COUNTER+=1done

example

#!/bin/bashwhile read line; doecho $linedone < /etc/passwd

example

Page 6: Licão 12 decision loops - statement iteration

while loop

$ vi while.sh #!/bin/bashecho –n “Enter a number: ”; read xsum=0i=1

while [ $i –le $x ]; dosum=$[sum+i]

i=$[i+1]done

echo “the sum of the first $x numbers is: $sum”

example

Page 7: Licão 12 decision loops - statement iteration

while loop

$ vi menu.sh#!/bin/bash

clear ; loop=ywhile [ “$loop” = y ] ;doecho “Menu”; echo “====”echo “D: print the date”echo “W: print the users who are currently log on.”echo “P: print the working directory”echo “Q: quit.”echoread –s choice # silent mode: no echo to terminalcase $choice in

D | d) date ;;W | w) who ;;P | p) pwd ;;Q | q) loop=n ;;*) echo “Illegal choice.” ;;

esacecho

done

example

Page 8: Licão 12 decision loops - statement iteration

until loop

until loop will execute the loop while the expression evaluates to false

while loop is perfect to execute a set of commands while some condition is true.

until loop is when u need to execute a set of cmds until a condition is true.

• Similar to the while structure. • until structure loops until the condition is true. “until this condition is true, do this”.

Syntax:

until commanddo Statement(s) to be executed until command is true done

• If the resulting value is false, given statement(s) are executed.

• If command is true then no statement would be not executed and program would jump to the next line after done statement.

Page 9: Licão 12 decision loops - statement iteration

until loop

#!/bin/sha=0 until [ ! $a -lt 10 ] do echo $a a=`expr $a + 1` done

example

0 1 2 3 456789

example result

Page 10: Licão 12 decision loops - statement iteration

until loop

#!/bin/bashCOUNTER=10until [ $COUNTER -lt 1 ]; dolet COUNTER-=1done

example

Page 11: Licão 12 decision loops - statement iteration

until loop

$ vi countdown.sh #!/bin/bash

echo “Enter a number: ”; read xecho ; echo Count Downuntil [ “$x” -le 0 ]; do

echo $x x=$(($x –1))sleep 1

done echo ; echo GO !

example

Page 12: Licão 12 decision loops - statement iteration

for loop

for loop Operates on lists of items. used when you are looping through a range of variables. It repeats a set of commands for every item in a list. statements are executed with var set to each value in the list

Syntax:

for var in word1 word2 ... wordNdo

Statement(s) to be executed for every word. done

• var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words).

• Each time the for loop executes, value of the variable var is set to the next word in the list of words, word1 to wordN.

Page 13: Licão 12 decision loops - statement iteration

for loop

#!/bin/shfor var in 0 1 2 3 4 5 6 7 8 9 do echo $var done

example span list numbers

0 1 2 3 4 5 6 7 8 9

example result

Page 14: Licão 12 decision loops - statement iteration

for loop

#!/bin/shfor FILE in $HOME/.bash* do echo $FILEdone

example display all the files starting with .bash and available in your home. executing from my root

/root/.bash_history/root/.bash_logout/root/.bash_profile/root/.bashrc

example result

Page 15: Licão 12 decision loops - statement iteration

for loop

#!/bin/bashlet sum=0for num in 1 2 3 4 5

dolet “sum = $sum + $num”done

echo $sum

example

Page 16: Licão 12 decision loops - statement iteration

for loop

#!/bin/bashfor i in $(ls); doecho $idone

example

#!/bin/bashfor i in $(seq 10); doecho $idone

example

Page 17: Licão 12 decision loops - statement iteration

for loop

#!/bin/bashfor x in paper pencil pendo

echo “The value of variable x is: $x”sleep 1

done

$vi for1.sh #!/bin/bash

for x doecho “The value of variable x is: $x”sleep 1

done

$ for1.sh arg1 arg2The value of variable x is: arg1The value of variable x is: arg2

if the list part is left off, var is set to each parameter passed to the script ( $1, $2, $3,…)

example

Page 18: Licão 12 decision loops - statement iteration

for loop

$ vi old.sh#!/bin/bash# Move the command line arg files to old directory.if [ $# -eq 0 ] #check for command line argumentsthenecho “Usage: $0 file …”exit 1

fiif [ ! –d “$HOME/old” ]thenmkdir “$HOME/old”

fiecho The following files will be saved in the old directory:echo $*for file in $* #loop through all command line argumentsdomv $file “$HOME/old/”chmod 400 “$HOME/old/$file”

donels -l “$HOME/old”

example

Page 19: Licão 12 decision loops - statement iteration

for loop

$ vi args.sh#!/bin/bash # Invoke this script with several arguments: “one two three“if [ ! -n “$1” ]; then

echo “Usage: $0 arg1 arg2 ..." ; exit 1 fi echo ; index=1 ; echo “Listing args with \”\$*\”:” for arg in “$*” ;do

echo “Arg $index = $arg” let “index+=1” # increase variable index by one

done echo “Entire arg list seen as single word.” echo ; index=1 ; echo “Listing args with \”\$@\”:” for arg in “$@” ; do

echo “Arg $index = $arg” let “index+=1”

done echo “Arg list seen as separate words.” ; exit 0

example

Page 20: Licão 12 decision loops - statement iteration

C-like for loop

An alternative form of for structure is

for (( EXPR1 ; EXPR2 ; EXPR3 ))do

statementsdone

• First, the arithmetic expression EXPR1 is evaluated.

• EXPR2 is then evaluated repeatedly until it evaluates to 0.

• Each time EXPR2 is evaluates to a non-zero value, statements are executed and EXPR3 is evaluated.

$ vi for2.sh #!/bin/bashecho –n “Enter a number: ”; read x

let sum=0for (( i=1 ; $i<$x ; i=$i+1 )) ; do

let “sum = $sum + $i”doneecho “the sum of the first $x numbers is: $sum”

Page 21: Licão 12 decision loops - statement iteration

select loop

select loop (fuction is like a for loop with menu selection)

Easy way to create a numbered menu from which users can select options.Useful for asking the user to choose one or more items from a list of choices.

Syntax:

select var in word1 word2 ... wordNdoStatement(s) to be executed for every word. done

• var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words).

• Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN.

• For every selection a set of commands would be executed with-in the loop.

loop was introduced in ksh and has been adapted into bash. It is not available in sh.

Page 22: Licão 12 decision loops - statement iteration

select loop

#!/bin/bashselect DRINK in tea cofee water juice appe all none do

case $DRINK in tea|cofee|water|all)

echo "Go to canteen" ;;

juice|appe) echo "Available at home"

;; none)

break ;; *) echo "ERROR: Invalid selection" ;;

esacdone

example let the user select a drink of choice (A)

Page 23: Licão 12 decision loops - statement iteration

select loop

$./test.sh 1) tea2) cofee3) water4) juice5) appe6) all7) none#? juiceAvailable at home#? none$

example result

Page 24: Licão 12 decision loops - statement iteration

select loop

$PS3="Please make a selection => " ; export PS3 $./test.sh 1) tea2) cofee3) water4) juice5) appe6) all7) nonePlease make a selection => juice Available at homePlease make a selection => none $

example alternate let the user select a drink of choice (B)

change the prompt displayed by the select loop by altering the variable PS3

Page 25: Licão 12 decision loops - statement iteration

Nesting while Loops

while loop as part of the body of another while loop

Syntax:

while command1 ; # this is loop1, the outer loopdo

Statement(s) to be executed if command1 is truewhile command2 ; # this is loop2, the inner loop do

Statement(s) to be executed if command2 is true done

Statement(s) to be executed if command1 is true done

Page 26: Licão 12 decision loops - statement iteration

Nesting while Loops

#!/bin/sha=0 while [ "$a" -lt 10 ] # this is loop1 do

b="$a" while [ "$b" -ge 0 ] # this is loop2 do

echo -n "$b " b=`expr $b - 1`

doneechoa=`expr $a + 1`

done

example add another countdown loop inside the loop used to count to nine

Page 27: Licão 12 decision loops - statement iteration

Nesting while Loops

0 1 0 2 1 0 3 2 1 0 4 3 2 1 0 5 4 3 2 1 0 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0

example result

echo -n option let echo to avoid printing a new line character

Page 28: Licão 12 decision loops - statement iteration

Loop Control

Loop control is needed to stop a loop or skip iterations of the loop two statements used to control shell loops

break statementcontinue statement

The infinite Loop

• loops have a limited life and they execute once the condition is false or true• loop may continue forever due to required condition is not met.

A loop that executes forever without terminating executes an infinite number of times.

Is called infinite loops.

#!/bin/sha=10 while [ $a -lt 10 ] do echo $a a=`expr $a + 1` done

Page 29: Licão 12 decision loops - statement iteration

Break statement

Break statement

Used to terminate the execution of the entire loop, after completing the execution of all of the lines of code up to the break statement. It then goes to the code following the end of the loop.

Syntax:

break

break command can also be used to exit from a nested loop using this format:

break n #n specifies the nth enclosing loop to exit from

.

Page 30: Licão 12 decision loops - statement iteration

Break statement

#!/bin/sha=0 while [ $a -lt 10 ] do

echo $a if [ $a -eq 5 ] then

break fi a=`expr $a + 1`

done

example loop would terminate as soon as a becomes 5

0 1 2 3 4 5

example result

Page 31: Licão 12 decision loops - statement iteration

Break statement

$ vi break.sh#!/bin/bash

LIMIT=19 echo echo “Printing Numbers 1 through 20, but something happens after 2 … ”a=0 while [ $a -le “$LIMIT” ]do a=$(($a+1)) if [ “$a” -gt 2 ] then

break fi

echo -n “$a ” done echo; echo; echo exit 0

example

Page 32: Licão 12 decision loops - statement iteration

continue statement

continue statement

Similar to break command

except that causes the current iteration of the loop to exit, rather than entire loop.

That is It causes a jump to the next iteration of the loop, skipping all the remaining commands in that particular loop cycle

This statement is useful when an error has occurred but you want to try to execute the next iteration of the loop.

Syntax:

continue

an integer argument can be given to the continue command to skip commands from nested loops:

continue n #n specifies the nth enclosing loop to continue from

.

Page 33: Licão 12 decision loops - statement iteration

continue statement

#!/bin/shNUMS="1 2 3 4 5 6 7" for NUM in $NUMS do Q=`expr $NUM % 2` if [ $Q -eq 0 ] thenecho "Number is an even number!!" continue fi echo "Found odd number" done

example

Found odd numberNumber is an even number!! Found odd numberNumber is an even number!! Found odd numberNumber is an even number!! Found odd number

example result

Page 34: Licão 12 decision loops - statement iteration

continue statement

$ vi continue.sh#!/bin/bash

LIMIT=19 echo echo “Printing Numbers 1 through 20 (but not 3 and 11)”a=0 while [ $a -le “$LIMIT” ]; do a=$(($a+1)) if [ “$a” -eq 3 ] || [ “$a” -eq 11 ] then

continue fi echo -n “$a ”

done

example