Lecture Twelve
More Scripting
Control Structures
if-then-elif-else
to control script according to number of arguments:
if [ $# = 0 ] thenecho Usage: cmd argument1 argument2 ... 1>&2 exit 1elif [ $# = 1 ]
then . .elif [ $# = 2 ]
then . .else
. .fi</code>
for-in
foris used to execute statements for a specifed number of repetitions- a loop variable takes the values of a specified list, one at a time
for example, to process a list of strings:
for animal in lion tiger bear do echo $animal doneto process the arguments passed to a script as a list of strings:
for var in $* do echo $var doneto process filenames in a directory, using command substitution:
for file in $(ls -a $1) do echo $file doneor, to process filenames in a directory, including path information:
for file in $1/* do echo $file done
for
forwithout the "in" keyword - loop variable takes value of variables $1, $2, $3, etc.for args # Note that "args" is a user-defined variable do echo $args done
while
- while control structure, loop while test remains true (0 return code)
to read from the keyboard:
while [ "$input" != end ] do printf "OK, give me more: " read input printf "You typed: '$input'\n" doneto read from a file:
while read input do echo "Input line is: $input" done < file1another way to read from a file:
cat file1 | while read input do echo "Input line is: $input" donenote that the file has to be opened to the while loop, not to the read statement
for example, the following would not work, the first line of the file would be printed continuously:
while read input < file1 do echo "Input line is: $input" done