| By Dave Taylor | Article Rating: |
|
| January 17, 2005 12:00 AM EST | Reads: |
9,791 |
If you've been hanging around programmers at all, you've already learned that they tend to think conditionally. Not, I hasten to say, that they conditionally think (though in some cases that might be true!) but that more than the general population, software developers are constantly musing about "if condition, then action."
What might surprise you is that the Linux shell offers identical capabilities, conditional statements that let you turn your command-line interaction - and, ultimately, your shell scripts - into powerful logic engines.
I'd like to spend some time looking at the basics of how to create conditional expressions on the command line, with the goal of being able to apply that to shell scripts too. I'll focus on Bash as it's my scripting shell of choice in the Linux (and Unix, and Mac OS X) environment, but everything we talk about is generally applicable to Csh and related shells too, albeit with slightly tweaked syntax.
Before I delve into conditionals, I hope you're starting to realize that one of the great things about choosing to learn programming by using shell scripts is that much of your learning actually takes place on a regular command line, and that as you become more sophisticated with command-line interaction (remember in my October column when we talked about >>&!, for example?), you'll also become more advanced as a shell script author. So don't get too distressed if you wonder why I haven't demonstrated even a one-line shell script several months into my column, okay?
Logical Expressions on the Command Line
Even neophyte Linux users have doubtless figured out that you can string a series of commands together by using the pipe symbol:ls -l * | wc -l
This causes the output of the "ls -l *" command to be fed to the "wc" command as input, creating a pipeline. It's a tremendously powerful capability and one of the best reasons to learn how to be a power Linux user.
What you might not have stumbled across is that you can specify multiple commands on a line by separating them with a semicolon:
ls -l * ; wc -l
Did you catch the logical error in the above command? While the ls works fine, sending its output to the screen, the wc command will appear to freeze because it's waiting for something to count, but there's no input specified so it just reads the keyboard. Type in a few lines, press ^D (control + D), and it'll indicate how many lines you just typed in.
Those are the easy, obvious ways to put two commands together. More interestingly, you can have a conditional execution joining two commands together too, where the second is run if and only if the first failed, or if and only if the first succeeded. The first is demonstrated by:
wc -l somefile || echo "can't find somefile to count"
In this case, if the wc command returns a non-zero return code (that is, fails: see the man page for wc to see what return codes it can specify by using "man wc" on the command line), the echo statement is run. If wc succeeds, though, the echo statement isn't run and the shell is done with the command sequence.
The opposite logic is achieved with:
wc -l somefile && echo "hope that's what you expect"
where the second command, the echo, is only run if the first command, wc, returns zero, that is, returns success. It worked; it did what you wanted it to, and it didn't encounter any errors along the way.
Expressions Within Expressions
Just to make this maximally complicated, you can also collect a set of commands into an expression with parentheses, so the following is a perfectly valid and legal Linux command:(grep dialup /var/log/modem | \
mail -s dialup taylor) || echo failed
In this final, complex example, we have a pipe that e-mails the output of a grep to the specified user with no output to the screen, unless the grep (or mail command) fails, in which case the word "failed" appears.
In daily use, the most common use for parenthesized expressions is to have a set of commands pushed into the background together:
(grep dialup /var/log/modem | mail -s dialup taylor) &
SIDEBAR
Due to an error, this column did not appear in the November issue of LWM. This article is #4 in the series and should have appeared before the December column, "Everything You Wanted to Know About the Test Command." To view the articles in the correct order, please go to http://linux.intuitive.com.
Published January 17, 2005 Reads 9,791
Copyright © 2005 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Dave Taylor
Dave Taylor, a contributing editor to Linux.SYS-CON.com, has been involved with the Linux and Unix community since 1980 and has written a number of best-selling Unix books. Currently, he writes, teaches, and works as a management consultant to tech startups, along with his new venture, Ask Dave Taylor!, www.askdavetaylor.com and his personal blog is www.blog.Linux.SYS-CON.com. To contact Dave, please go to /www.intuitive.com/contact.shtml.
- Ubuntu-based Open Source Linux Mint Tests KDE Version
- Linux Virtualization and Tired Open Source Myths
- IGEL Supports Red Hat Enterprise Virtualization 3.0
- CloudLinux Announces Support for Atomia
- Amazon Kindle Fire Gets Its Own 'Personal Cloud Desktop' with AlwaysOnPC App Launch
- SPIRIT DSP Receives 2011 INTERNET TELEPHONY Product of the Year Award
- Hadoop Quickstart: Use Whirr to automate standup of your distributed cluster on Rackspace
- Jury Gets Novell Antitrust Case Against Microsoft
- The Utility Infrastructure Security Market 2012-2022: Cybersecurity & Smart Grids
- FORTUNE Magazine Names Rackspace Among “100 Best Companies to Work For”
- EnterpriseDB Announces Availability of Postgres Plus Cloud Database
- iFollowOffice Turns to Virtual Bridges and Savvis for On-Demand Virtual Desktop Services
- i-Technology in 2012: Five Industry Predictions
- Ubuntu-based Open Source Linux Mint Tests KDE Version
- Amazon to Rent Out Supercomputers
- Amazon Émigré Starts Network Monitoring Firm
- HP’s Putting a Back Door in the Itanium Alamo
- Linux Virtualization and Tired Open Source Myths
- CloudLinux Announces Preferred Partner Program
- MapR Pushes the Hadoop Envelope
- Rightware Announces Gaming Performance Benchmark for OpenGL ES 3.0/Halti
- IGEL Supports Red Hat Enterprise Virtualization 3.0
- CloudLinux Announces Support for Atomia
- 3Dconnexion Announces its Newest 3D Mouse - the SpaceMouse Pro
- The i-Technology Right Stuff
- Linux.SYS-CON.com Exclusive: Linus Discloses *Real* Fathers of Linux
- After Ubuntu, Windows Looks Increasingly Bad, Increasingly Archaic, Increasingly Unfriendly
- A Closer Look at Damn Small Linux
- Linus' Top Ten SCO Barbs
- SCO CEO Posts Open Letter to the Open Source Community
- Netscape Co-Founder's 12 Reasons for Growth of Open Source
- Where Are RIA Technologies Headed in 2008?
- *POINT - COUNTERPOINT SPECIAL* What's Wrong with the Open Source Community?
- Introducing "Cooperative Linux" - Linux for Windows, No Less
- Linux.SYS-CON.com Exclusive: What Would UserLinux Look Like?
- Why Recovering a Deleted Ext3 File Is Difficult . . .


















