Never say "If" writing a Bash script! (Exit codes & logical operators)

Watch on YouTube

Show annotations

Download is disabled.

73,118

3,522

187

Genre: Science & Technology

License: Creative Commons Attribution license (reuse allowed)

Family friendly? Yes

Wilson score: 0.9421

Rating: 4.7983 / 5

Engagement: 5.07%

Luke Smith

Subscribe | 83.3K

Shared March 19, 2020

A good rule of thumb is to never use "if" statements when writing shell or bash scripts. 90% of the time, you can get what you want more elegantly just with logical operators like && and ||. It makes the difference between ugly and elegant looking and running code.

WEBSITE: https://lukesmith.xyz 🌐❓🔎
DONATE NOW: https://lukesmith.xyz/donate 💰😎👌💯


MagellanLinux

Boomer avoids the stress of the apocalypse by obfuscating his bash scripts

3 weeks ago | [YT] | 472

Peter Bonnema

This is how to not write an if when you actually mean 'if'. How is not writing what you mean improving readability?

Also, your example is not so much about the if-statement as it is about errorhandling. But if you are doing a video about errorhandling, then do it properly and talk about signal traps and all that kind of stuff.

2 weeks ago (edited) | [YT] | 46

Nerd Bot

Some additional info for new users:
- 0 is considered True, while anything not 0 is considered False by the logical operators. This is the opposite of what you may expect if you come from a programming language like Java.
- The logical operators check the exit values of the functions/scripts (a number), not the pipe output. For example, "cat" - like any other program/process returns an exit code (you don't see it on screen) like Luke mentioned, but this is completely independent of the output you see in the shell. What you see is the content the program piped into stdout and/or stderr, here the file's content and the human readable error respectively.
- if you want to see what the exit code actually was, run "echo $?". $? is a special variable (at least in bash) that contains the exit code of the LAST command that ran. I changed in my bash_profile the prompt variable PS1 to always display exit codes if they're not 0, which is quite handy
- The reason why && and || work like this is optimization. Both of them will stop evaluating once the result can't change anymore. For example, if you have an expression like "a && b && c" and lets say b failed, the result of expression can only be False, regardless what c returns - which is why it will not be run. Same goes for "a || b || c". Once a or b succeeded, there's no need to run anything after that since it won't change the outcome anymore. You might see programmers use that quirk when writing code, not only in shell scripts. But there might be poorly designed languages out there which specification or implementation will not guarantee this behaviour - just as they might have different approaches on how to handle the Dangling-Else-Problem. Understanding/Knowing these things are one of the pillars of truly mastering a programming language
- When trying to understand the logic, approach the operators from left to right, evaluate the operator using it's left and right parameter, substitute the result and continue. For example, when having "a && b || c && d":
- "a && b || c && d" => Evaluate "a && b" and call that e
- "e || c && d" => Evaluate "e || c" and call that f
- "f && d" => Evaluate for the final result
- There's also the concepts of grouping and subshells that you can use inside of conditional statements, but that might be part of another video... Brackets in shell scripting can be a bit intimidating/confusing for newbees (like pointers in C)
- Operator precedence is always left to right and not AND before OR as you might expect. If you need a different precedence, use the afore mentioned concept of grouping to implement this. See https://www.gnu.org/software/bash/manual/html_node/Command-Grouping.html for details

3 weeks ago (edited) | [YT] | 157

stinoslus

: ${EDITOR:=nano}

3 weeks ago | [YT] | 137

Lo-Res Gamer

You and I have different definitions of "elegance". I can understand your preference for concise code, which is the traditional spirit of Unix/Linux. I, on the other hand, want my code to be readable by newbs in a corporate environment long after I've gone. I don't really consider your examples obscure for someone who has knowledge of bash, but using structures (like if statements) that are recognizable to users of other programming languages with no training in bash is also "elegant"

1 week ago (edited) | [YT] | 7

Santiago González Rojo

In many common programming languages you can do stuff like that, but in the Software Industry it's considered to be unreadable code, and a bad practice

2 weeks ago | [YT] | 43

John Koelndorfer

"Never use 'if' statements when writing shell scripts" is bad advice. Making use of logical operator short-circuiting is a shortcut, and shortcuts make your code less maintainable and less readable. I took a look at your `mw` in your mutt-wizard repo on GitHub. The lack of if-statements (and whitespace in general) makes the code exceptionally dense and harder to follow than it otherwise would be.


Also, I am not a regular follower of your channel so I don't know if you have some rationale for this, but using teaching folks to use strictly POSIX shell seems like a mistake to me. Bash and other GNU coreutils offer so many niceties, and most folks will only ever run Linux anyhow.

1 week ago | [YT] | 5

RUNIE

When explaining the logic between &&, the word you're looking for is short-circuiting.

3 weeks ago | [YT] | 60

Urban

check out 'man test' for expressions similar to [ -z "$VAR" ]

3 weeks ago (edited) | [YT] | 39

oh

Yeah, yeah, you can cut down on everything and make oneliners. If you write code like this at work, I will punch you.

Write easily readable code, so it's easy to spot your damn bug.

2 weeks ago | [YT] | 26

Sad Face

Terry Davis always said that the CASE statement was divine

3 weeks ago | [YT] | 72

Night Fury

Corona-chan is helping me learn bash script :)

3 weeks ago | [YT] | 47

damirahman

less readable and fewer keywords =/= elegant

1 week ago | [YT] | 6

Nope

It's worth noting that Luke uses these compact forms in a way that makes his code more legible.

3 weeks ago | [YT] | 35

Kai Hendry

I’m a `if test` kinda guy 😂 .. it looks better to me.

3 weeks ago | [YT] | 32

Logan Wood

roads && abolish-roads

3 weeks ago | [YT] | 30

Cranked

Code quality is one of the most important things and by doing "shorter" "more elegant" code, you'll loose on code quality. This is not good advice. If you're searching for a bug in your bash script and you're checking all the "if" statements, then this would be a horrible way to tell apart normal script from an indented if statement. Why aren't you doing everthing in one line? Would be more elegant, or wouldn't it?

1 week ago | [YT] | 8

m0gria

One more thing: The following does not equal to an if else:


condition && statement1 || statement2

because if the condition is true and the statement1 fails statement2 will be executed as well!

1 week ago | [YT] | 3

SimGunther

Instructions unclear; ended up with a plan 9 emulator in a bash script.

3 weeks ago | [YT] | 25

Ivy / Ducklett

You kinda sound like the average javascript programmer advocating for ternary statements and map() over if and loops not gonna lie 👀

3 weeks ago | [YT] | 21