Repetition Structures

9
REPETITION STRUCTURES

Transcript of Repetition Structures

REPETITION STRUCTURES

QUESTION

• What are some reasons to repeatedly execute commands?

• What are some tasks that we can/do perform on our machines regularly?

LOOPING IN SCRIPTS

• Loops are used to perform a set of commands repeatedly until a condition is met to terminate them.

• Question: What are some programs you wrote in CIS120 that used loops?

• While we can use the loops the same in each language a distinction has to be made for scripting.Programming Scripting

FOR LOOP

• The For Loop is a looping structure used to execute a set of commands a specified number of times.

– for var in <list> do

commandcommand

done

• In programming you would specify a range to execute your loops. Ex. 1 -100, 2-10

• In scripting, for loops are much more powerful than just executing ranges:

– Range: Run for a predefined set of numbers

– List: A list of values or files– List/Range: A list with a naming

scheme– Directory: A directory to manipulate

some or all the files

EXAMPLE: FOR LOOPS

• Exercise in Learning Materials– Identify what the for loop is doing:

• for1.txt• for2.txt• for3.txt• for4.txt

WHILE LOOP

• The While Loop is a looping structure that executes as long as a condition is true(exit status of 0).

– while [ condition ] docommandcommand done

• Question: What are some conditions that we can execute a while loop over?

• There is another type of loop known as an Until Loop that executes while a condition is false.

• Question: What is the exit status being tested for an Until loop?

• Question: How could we alter a while loop to behave in the same way as an Until loop?

EXAMPLE: WHILE LOOPS

• Exercise in Learning Materials– Identify what the while loop is doing:

• while1.txt• while2.txt• while3.txt

I/O REDIRECTION ON A LOOP

REDIRECT OUTPUT• for i in 1 2 3 4 do echo $i done > loopout.txt

• for file do echo “Process $file” > &1 done > output

• while [“$endofdata” –ne TRUE ] do … done 2 > errors

REDIRECT INPUT

• while read n do run $n done < installFile.txt

• You can override redirection of the entire loop’s input or output by explicitly using the redirect commands.

– <, >

BREAK AND CONTINUE

BREAK• The Break command is often used

to terminate the remainder of a loop

• Used to create a condition where if an undesirable outcome was to happen you can test for it and break the loop.

– Ex. If disk space is low stop processing files immediately

• break

CONTINUE

• The Continue command is used to terminate the current iteration of a loop.

• Used to test if an undesirable outcome happens and then to start a new iteration of the loop.

– Ex. If you are updating files and one doesn’t exist, proceed to the next one.

• continue