Course contentsShow
← Linux
Lesson 127 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Conditional Execution Strategies

Master logic branching using logical operators instead of nested conditionals.

In this lesson, you will learn how to flatten complex, "nested" decision trees by using logical operators to make your scripts cleaner and more efficient.

Beyond the Nested if

When you are writing scripts, you often need to check multiple conditions before running a command. Beginners often fall into the trap of "nested conditionals"—putting an if statement inside another if statement. This creates "arrow code" that is hard to read and difficult to debug.

Instead, we use Logical Operators: && (AND) and || (OR).

These operators allow the shell to evaluate conditions in a single line. Because the shell evaluates these from left to right, we can stop execution as soon as a requirement fails.

The Logic of Efficiency

Think of && as a "gatekeeper." The command to the right will only execute if the command to the left exits with a success code (0).

Imagine you want to check if a configuration file exists and if it is writable before you attempt to append text to it:

# Instead of nested if statements:
[ -f "/etc/myapp.conf" ] && [ -w "/etc/myapp.conf" ] && echo "Ready to update" >> "/etc/myapp.conf"

In this example, the shell performs a mini-logic test:

  1. Does the file exist? If no, stop.
  2. If yes, is it writable? If no, stop.
  3. If yes, proceed to the write operation.

If you need an "OR" logic, use ||. This is perfect for error handling. You can attempt a command and immediately trigger a fallback or exit if it fails:

# Try to copy a file, or print an error if the copy fails
cp source.txt backup.txt || echo "Backup failed!"

Why Flatten?

By using these operators, you avoid the "pyramid of doom" where your code drifts further and further to the right side of your screen. It keeps your logic flow linear, readable, and highly efficient. You are effectively leveraging the shell’s internal understanding of exit codes to control the execution path without needing redundant if structures.

Key Takeaway: Replace deep nesting with && and || to create concise, readable, and linear conditional execution flows.