Database Reference
In-Depth Information
Sending invitation to chloe.graham66@example.com.
Sending invitation to wyatt.nelson80@example.com.
Sending invitation to peter.coleman75@example.com.
In this case we need to use a
while
loop because Bash does not know beforehand
how many lines the input consists of.
Although the curly braces around the
line
variable are not necessary in this case
(because variable names cannot contain periods), it's still good practice.
This redirection can also be placed before
while
.
You can also provide input to the
while
loop interactively by specifying the special
file standard input
/dev/stdin
. Press
<Ctrl-D>
when you're done:
$
while
read
i;
do
echo
"You typed: $i."
;
done
< /dev/stdin
one
You typed: one.
two
You typed: two.
three
You typed: three.
This method, however, has the disadvantage that, once you press
<Enter>
, the com‐
mand(s) between
do
and
done
are run immediately for that line of input.
Looping Over Files
In this section, we discuss the third type of item that we often need to loop over: files.
To handle special characters, use
globbing
(i.e., pathname expansion) instead of
ls
:
$
for
filename in *.csv
>
do
>
echo
"Processing ${filename}."
>
done
Processing countries.csv.
Just as with brace expansion with numbers, the
*.csv
is first expanded into a list
before it is processed by the
for
loop. A more elaborate alternative to finding files is
find
(Youngman, 2008), which:
• Allows for elaborate searching on properties such as size, access time, and per‐
missions
• Handles dashes
• Handles special characters such as spaces and newlines
$
find data -name
'*.csv'
-exec
echo
"Processing {}"
\;
Processing data/countries.csv