Work the Shell - Conditional Statements and Flow Control
The last of the basic building blocks of shell scripting are conditional statements, allowing you to decide programmatically whether to execute a block of statements based on a logical test, and flow control statements, the great innovation from the earliest days of programming where you could have a block of code execute more than once. We explore both of these in this column and, finally, are done with the proverbial Lego blocks of scripting, allowing us to start exploring how to solve complex scripting problems with novel and unique combinations of simple statements.
The most obvious conditional statement is if-then-else, which in shell scripting looks like:
if condition ; then ; statements ; else ; statements2 ; fi
Of course, you'd usually see this on multiple lines, so it's more likely to look like this:
if condition; then statements else statements2 fi
There are some variations on this, including safely omitting any sort of else clause, but more interestingly, you can “chain” conditionals together with an else if structure:
if condition; then statements elif condition2 ; then statements2 fi
That's perfectly valid and, worth noting, functionally different from the structure:
if condition
then
statements
if condition2; then
statements2
fi
fi
The difference will be obvious to anyone who has programmed before. In the first example, statements2 would execute if condition was false and condition2 were true. In the latter example, however, statements2 would be executed only if condition were true and condition2 were true. Subtle, but very important!
Specific logical conditions can take on a wide variety of appearances, because the only requirement for a conditional expression is that it return zero if the evaluated condition is false and nonzero if it should be considered true. Indeed, there are commands in Linux called false and true, so you can use statements like “if true; then....” Most conditions, however, are built around the invaluable test command, with its many different flags and options.
Want to compare two string (text) values? You could use:
if test $myvar = "exit" ; then
or its shortcut alternative of:
if [ $myvar = "exit" ] ; then
Compare two numeric values with:
if test $numval -lt 10 ; then
There's also a world of file and variable tests available in the test command too, including -r to test if a file is readable, -e to see if it exists at all, -s to see if the file exists and has a nonzero size, and -d to test for a directory and -f to test for a regular file.
So if you want to differentiate whether $filename is a file, directory or other file type, you could use a statement sequence like:
if test -f $filename ; then echo "$filename is a regular file" elif test -d $filename ; then echo "$filename is a directory" else echo "$filename is neither a file nor a directory." fi
Check out the test man page (use man test) to read about all the many different conditionals you can use in a shell script.
There are a number of different looping and flow control structures above and beyond simply the if-then-else conditional, luckily, and here are the big three:
for x in y; do; statements; done
while x; do; statements; done
case x in ; condition1) statements ;; condition2) statements ;; esac
There are more conditional statements, but you'll find that in the vast majority of cases, having for loops, while loops, case statements and if-then-else statements will serve as the building blocks of even the most complex script.
The for loop is particularly useful in its variations. Want to step through the parameters given to the shell script itself? Use something like this:
for value ; do ; statements ; done
Want to step through a set of matching filenames for a given pattern? Here's how to do that in a script:
for filename in *.c ; do statements done
Let's look at how a couple of these can be combined in useful ways, rather than just duplicate the man page, however. Here's a simple script that examines each entry in the current directory, indicating whether it's a file or directory:
for name in *
do
if [ -f "$name" ] ; then
echo "$name is a file"
elif [ -d "$name" ] ; then
echo "$name is a directory"
else
echo "$name is neither a file nor directory"
fi
done
For illustrative purposes, let's try another version of this script, one that recognizes *.c as C source files, *.h as included header files and *.o as intermediate object files, but this time we'll use the case statement:
for name in *
do
case "$name" in
*.c ) echo "$name is a C source file" ;;
*.h ) echo "$name is a header file" ;;
*.o ) echo "$name is an object file" ;;
esac
done
From a readability perspective, the case statement is hard to beat!
Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- RSS Feeds
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- Developer Poll
- Dart: a New Web Programming Experience
- May 2013 Issue of Linux Journal: Raspberry Pi
- What's the tweeting protocol?
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




2 hours 54 min ago
3 hours 41 min ago
5 hours 14 min ago
6 hours 51 min ago
8 hours 49 min ago
9 hours 6 min ago
9 hours 36 min ago
9 hours 37 min ago
9 hours 37 min ago
12 hours 38 min ago