Flow-of-control statments



Last revision August 6, 2004

if and foreach are the basic flow-of-control statements. There are more advanced ones named switch and while which are similar to the statements of the same name in the C language.

if

The if command allows you to conditionally execute a command or set of commands depending upon whether some expression is true. There are two forms.

foreach

This statement allows you to execute a loop, like a do statement in Fortran or a for statement in C.

The syntax is:

foreach and end are keywords. The end statement must be on a line by itself.

name is the name of a variable that you create. This is the "loop index".

(wordlist) is a list of "words", meaning any character strings separated by blanks. The parentheses are required. The "word list" can be a list of actual constant values, or the results of variable substitution, arithmetic expressions, or command substitution.

When the foreach statement is encountered in a shell script, the wordlist is evaluated (necessary variable and command substitutions and expressions are done) and stored. Then the new variable name is set equal to the first word in the list and the block of statements is executed. When the end statement is reached, the script goes back to the foreach line and sets the variable name equal to the next word in the list and executes the block of statements again. This is done over and over until all words in the wordlist have been used up.

This type of looping statement is good for repetitively executing the same commands for a set of arguments. For example, you could check all the arguments given to the shell to see if they are plain files, and if so, make backup copies, using these statements in a shell script:

The foreach command can also be used interactively from the terminal. In this form, you will get question mark prompts (?) to enter your commands. When done, type end after one of these prompts. For example, you could type the following commands interactively at your terminal to make backup copies of all Fortran programs in your current directory: