Chapter 1. A Big “if” Idiom
To get you started in understanding bash idioms, we’ll look at a bash construct that allows you to do what you might normally do with an if/then/else construct but with sparser syntax. The idiomatic expression we’ll show you in this chapter has some real advantages—mostly terseness—and some pitfalls to avoid. But if you don’t know bash idioms, you might not recognize or realize what is going on.
Take a look at this piece of code:
[[-n"$DIR"]]&&cd"$DIR"
Do you think that looks like an if statement? If you’re conversant in bash, you’ll recognize that it is functionally the same thing; you’ll understand it as an if statement even though the if keyword doesn’t appear in the code.
What’s going on?
The Big “if”
To explain this idiom, let’s first look at a similar but simpler example:
cdtmp&&rm scratchfile
This too, is, in effect, an if statement. If the cd command succeeds, then (and only then) execute the rm command. The “idiom” here is the use of the double ampersand (&&), typically read as “and,” to separate the two commands.
Logic or philosophy classes teach the rule: the expression “A AND B” is true if and only if both A and B are each true. Therefore if A is false, there is no need to even consider the value of B. For example, consider “I own a dog AND I own a cat.” If I do not own a dog, then this compound expression is false for me, regardless of my cat situation.
Let’s apply this to bash. Remember that the basic function of bash is to execute ...
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.
Read now
Unlock full access