CPS 393 Lecture Notes - Lecture 4: Infinite Loop, While Loop, Texas State Highway Loop 1

68 views5 pages
Lecture 4: Loops, variable scope, regex, brog style
lecture
While loop:
typical conditional loop
syntax:
while command(s)
do
actions
done
Pre-amble to example 2:
read oneline < myfile # opens myfile stores the 1st line into oneline
echo $oneline # prints out the same 1st line
read oneline < myfile
echo $oneline
how do we make this happen repeatedly? use a while loop
# EXAMPLE 1
month=1
while [ ${month} -le 12 ] # le is a less than or equal to operator
do
someprocess ${month}
month=$(( ${month}+1 )) # $ with double parentheses means an arithmetic expression -
- treats the stuff inside as numbers
done
# EXAMPLE 2 --- INCORRECT VERSION
while read wholeline < inputfile
do
someaction $wholeline
done
# infinite loop
# file being opened every single time
# so you only read the 1st again repeatedly
# EXAMPLE 2 --- CORRECT VERSION
while read wholeline # reads everything upto (not including) the newline char
do
echo $wholeline
done < inputfile
# we are only opening the file once
# whenever the read command is run in this case,
# it continues reading 1 line at a time till the end of the file
# when read returns false
# it exits the body of the loop
1
2
3
4
5
6
7
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
8
9
10
11
12
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.

Already have an account? Log in
Processing command line arguments (Method 1):
Recall: cat intro ch1 ch2 ch3 appendix
cat command can look at command line (CL) args
but does not specify # of args
Want: myscript pear apple …
as many CL args as you want
Until:
Just like the while loop
but its logic condition is reversed
until this condition is false
the loop executes
once it is true
it ends
THIS IS NOT A DO-WHILE LOOP
syntax:
until [ end-condition ]
do
….
done
For
not a counted loop like in BASIC, Pascal, etc
think “iterative substitution”, similar to python
syntax:
for variable in val1 val2 …
do
action(s)
done
# EXAMPLE 3 -- METHOD 1
while [ $1 ]
do
# action on $1
shift # everything slides over to the left
# string at $3 is now at $2, $2 is now at $1, and so on
# until there is no $1 left, and the while loop exits
done
# EXAMPLE 1 -- MULTIPLE RENAME
# DOS version: ren assig* assig*.bak <-- to rename all files
# this is NOT the same as Unix with the mv command
for filevar in assig*
do
mv ${filevar} ${filevar}.backup
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$10 USD/m
Billed $120 USD annually
Homework Help
Class Notes
Textbook Notes
40 Verified Answers
Study Guides
1 Booster Class
Class+
$8 USD/m
Billed $96 USD annually
Homework Help
Class Notes
Textbook Notes
30 Verified Answers
Study Guides
1 Booster Class