Loops Flashcards
!/usr/bin/env bash
FOR loop1
for x in one two three four
do
echo number $x
done
output:
number one
number two
number three
number fourFORl
What exactly happened? The “for x” part of our “for” loop defined a new environment variable (also called a loop control variable) called “$x”, which was successively set to the values “one”, “two”, “three”, and “four”. After each assignment, the body of the loop (the code between the “do” … “done”) was executed once. In the body, we referred to the loop control variable “$x” using standard variable expansion syntax, like any other environment variable. Also notice that “for” loops always accept some kind of word list after the “in” statement. In this case we specified four English words, but the word list can also refer to file(s) on disk or even file wildcards.
!/usr/bin/env bash
FOR loop2
for myfile in /etc/r*
do
if [-d “$myfile”]
then
echo “$myfile (dir)”
else
echo “$myfile”
fi
done
output:
/etc/rc.d (dir)
/etc/resolv.conf
/etc/resolv.conf~
/etc/rpc
The above code looped over each file in /etc that began with an “r”. To do this, bash first took our wildcard /etc/r* and expanded it, replacing it with the string /etc/rc.d /etc/resolv.conf /etc/resolv.conf~ /etc/rpc before executing the loop. Once inside the loop, the “-d” conditional operator was used to perform two different actions, depending on whether myfile was a directory or not. If it was, a “ (dir)” was appended to the output line.
!/usr/bin/env bash
FOR loop 3
for thing in “$@”
do
echo you typed ${thing}.
done
output:
$ allargs hello there you silly
you typed hello.
you typed there.
you typed you.
you typed silly.
Of course, it’s often handy to perform loops that operate on a script’s command-line arguments. Here’s an example of how to use the “$@” variable
WHILE loop1
myvar=0 while [$myvar -ne 10] do echo $myvar myvar=$(( $myvar + 1 )) done
“While” statements are typically used to loop a certain number of times, as in the following example, which will loop exactly 10 times
UNTIL loop1
myvar=0 until [$myvar -eq 10] do echo $myvar myvar=$(( $myvar + 1 )) done
“Until” statements provide the inverse functionality of “while” statements: They repeat as long as a particular condition is false. Here’s an “until” loop that functions identically to the previous “while” loop