Loops Types of Loops Bash has several types

Loops

Types of Loops • Bash has several types of loops. We’ll learn two: • A while loop, for indefinite iteration • A for loop, for definite iteration

The While Loop • The while loop has the following general form while <condition> ; do <statements> done

The While Loop, Continued • Here is a segment of code that prompts the user to enter the name of an existing file, and continues until they do echo “Please enter the name of a file that exists” read FNAME while [ ! -f $FNAME ] ; do echo $FNAME ” doesn’t exist. read FNAME done Enter another name”

The For Loop • The for loop has the following general form for <variable> in <list of values> ; do <statements> done • Recall that the only data type in Bash is the string. Thus, for loops can only iterate over lists of strings.

The For Loop, Continued • An example for loop for PET in dog fish cat ; do echo $PET “is a nice pet. ” done

Using the For Loop With Files • A common use of the for loop is to iterate over all the files in the directory. To do that, you can create a list of files using wildcard characters. #!/bin/bash # This program prints a list of the files in a directory that are executable EXECS="” # Initialize variable to empty string. for A_FILE in * ; do # the –x test returns true if its argument exists and is executable if [ -x $A_FILE ] ; then EXECS="$EXECS $A_FILE" # Concatenate the file onto the list # The double quotes are necessary. fi done echo "These files are executable: " $EXECS Why?

For Loops That Iterate Over Integers • By definition, for loops iterate over lists of strings. • If we want to iterate over ints, we have to create a list containing the string representations of ints: “ 1 2 3 4 5 …”. • The seq command does just that. • Seq takes a range of ints from the command line, and prints out all the ints in the range on the standard output. • The syntax of seq is seq <first int> <optional increment> <last int> • Example % seq 1 10 1 2 3 4 5 6 7 8 9 10

For Loops That Iterate Over Integers, Continued • The touch command creates an empty file with the name specified on the command line. • Example % ls a. txt b. txt % touch foo. txt % ls a. txt b. txt foo. txt

For Loops That Iterate Over Integers, Continued • Let’s create 10 files named t 0. txt, t 1. txt, … t 9. txt #!/bin/bash for N in `seq 0 9` ; do # ` is backquote FNAME=t$N. txt touch $FNAME done # This works because. can’t be part of a variable name
- Slides: 10