Database Reference
In-Depth Information
8464
8836
9216
9604
10000
There are a number of things going on here:
Bash has a feature called brace expansion, which transforms {0..100..2} into a
list separated by spaces: 0 2 4 ... 98 100 .
The variable i is assigned the value 1 in the first iteration, 2 in the second itera‐
tion, and so forth. The value of this variable can be employed in commands by
prefixing it with a dollar sign ( $ ). The shell will replace $i with its value before
echo is executed. Note that there can be more than one command between do
and done .
We pipe the output of the for loop to tail so that we see the last ten values, only.
Although the syntax may appear a bit odd compared to your favorite programming
language, it's worth remembering this because it's always available in the Bash shell.
We'll shortly introduce a better and more flexible way of repeating commands.
Looping Over Lines
The second type of items we can loop over are lines. These lines can come from either
a file or from standard input. This is a very generic approach because the lines can
contain anything, including numbers, dates, and email addresses.
Imagine that we want to send an email to our customers. Let's generate some fake
users using the Random User Generator API :
$ cd ~/book/ch08
$ curl -s "http://api.randomuser.me/?results=5" > data/users.json
$ < data/users.json jq -r '.results[].user.email' > data/emails.txt
$ cat data/emails.txt
kaylee.anderson64@example.com
arthur.baker92@example.com
chloe.graham66@example.com
wyatt.nelson80@example.com
peter.coleman75@example.com
We can loop over the lines from emails.txt with a while loop:
$ while read line
> do
> echo "Sending invitation to ${line}."
> done < data/emails.txt
Sending invitation to kaylee.anderson64@example.com.
Sending invitation to arthur.baker92@example.com.
Search WWH ::




Custom Search