Skip to Content
Shell Scripting: Expert Recipes for Linux, Bash, and More
book

Shell Scripting: Expert Recipes for Linux, Bash, and More

by Steve Parker
August 2011
Beginner to intermediate
600 pages
14h 29m
English
Wrox
Content preview from Shell Scripting: Expert Recipes for Linux, Bash, and More

For Loops

Unlike most loops, the for loop does not test the condition of a variable each time it goes around the loop. Instead, it starts with a list of items to iterate through and works its way through them until it has reached the end. This makes it the most deterministic of the loop structures. This does not mean that the list of items has to be written out explicitly in the script itself (although it can be, and often is). It can iterate through each of the words in a file, through the content of a variable, or even through the output of other commands. The simplest form of for is to give it a set of items to work through, however.

download.eps

$ cat fruit.sh
#!/bin/bash
for fruit in apple orange pear
do
  echo "I really like ${fruit}s"
done
echo "Let's make a salad!"
$ ./fruit.sh
I really like apples
I really like oranges
I really like pears
Let's make a salad!
$

fruit.sh

What happens here is that you define a variable, fruit, which is set in turn to apple, then orange, then pear. This loops around three times until it has exhausted its list. The first time around the loop is fruit=apple; the second time, fruit=orange; and on the third and final iteration, fruit=pear. Once it has completed the loop, the script continues normal execution with the next command after the done statement. In this case, it ends by saying “Let’s make a salad!” to show that it has ended the loop, but not the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Command Line and Shell Scripting Techniques

Linux Command Line and Shell Scripting Techniques

Vedran Dakic, Jasmin Redzepagic
Linux Shell Scripting Cookbook - Third Edition

Linux Shell Scripting Cookbook - Third Edition

Clif Flynt, Sarath Lakshman, Shantanu Tushar

Publisher Resources

ISBN: 9781118166321Purchase bookDownloads