Skip to main content

πŸ“˜ ** Command Chaining using **cmd1 || cmd2


🎯 What You Will Learn​

  1. Understand the logical OR (||) operator in Bash command chaining.
  2. Learn how to execute the second command only if the first command fails.
  3. Explore practical examples with expected outputs.
  4. Apply OR chaining for WordPress CLI, server checks, and automation recovery.
  5. Learn differences between ||, &&, and ; chaining for decision logic.
  6. Implement fault-tolerant Bash scripts using conditional chaining.

1. 5W + 1H Framework​

ElementDescription
WhatThe `
WhyIt allows you to define a fallback or recovery action when the first command doesn’t succeed β€” improving reliability and error handling.
WhoUseful for system administrators, DevOps engineers, WordPress VPS managers, and automation script developers.
WhenUsed when you want an alternative command to execute if the first one fails β€” such as restarting a service, running diagnostics, or logging errors.
WhereCommonly used in Bash scripts, CLI tasks, and WP-CLI automation loops.
HowThe shell checks the exit status of the first command. If it’s non-zero (error), it proceeds to execute the second command. Otherwise, it skips it.

2. Prerequisites​

  • Basic understanding of:
  • Linux shell (Bash)
  • Exit status codes ($?)
  • Simple command execution
  • Access to a terminal (root or sudo privileges)
  • WordPress CLI (for applied examples)

3. Core Syntax & Concept​

NoSyntax FormulaSyntax ExampleExplanationExpected Behavior
1`cmd1cmd2``ls /invalid/dir
2`(cmd1)(cmd2)``(wp plugin update --all)
3`cmd1 argexit 1``systemctl restart nginx
4`cmd1cmd2
5`test expressioncmd2``[ -f /etc/passwd ]
6`falsetrue``false

4. Behavioral Flow Diagram​

+-------------+
| Run cmd1 |
+-------------+
|
v
+--------------+
| cmd1 success?|
+--------------+
| |
YES NO
| |
v v
Skip cmd2 Run cmd2

Key logic: β†’ If cmd1 succeeds (exit code 0), Bash skips cmd2. β†’ If cmd1 fails (non-zero exit code), Bash executes cmd2.​

5. Practical Examples with Expected Output​

Example 1 – Basic File Check​

cat /etc/unknown.conf || echo "File missing!"

Expected Output:

cat: /etc/unknown.conf: No such file or directory
File missing!

Explanation: cat fails because the file doesn’t exist β†’ triggers the fallback echo.​

Example 2 – WordPress Plugin Recovery​

wp plugin update --all --allow-root || wp plugin list --allow-root

Expected Output (if update fails):

Error: Could not connect to WordPress database
+----------------------+----------+
| name | status |
+----------------------+----------+
| akismet | active |
| litespeed-cache | active |
+----------------------+----------+

Use Case: Automatically lists plugins for debugging if the update process fails.​

Example 3 – Server Service Check​

systemctl restart redis-server || echo "Redis restart failed!"

Expected Output:

Redis restart failed!

Explanation: The message only appears if Redis cannot restart.​

Example 4 – Website Ping Fallback​

ping -c 2 wpstrategist.com || ping -c 2 metaxenith.com

Expected Output (if wpstrategist.com unreachable):

PING metaxenith.com (xxx.xxx.xxx.xxx): 56 data bytes
64 bytes from metaxenith.com: icmp_seq=0 ttl=57 time=35.4 ms

Explanation: If the first domain is down, the second becomes the fallback check.​

Example 5 – Automation Recovery​

mkdir /root/wpbackup || echo "Backup directory already exists!"

Expected Output:

mkdir: cannot create directory β€˜/root/wpbackup’: File exists
Backup directory already exists!


6. Use Cases in WordPress VPS​

Use CaseCommandPurpose
Plugin auto-check`wp plugin update --all
Redis check`redis-cli ping
PHP restart fallback`systemctl restart php8.3-fpm
Backup safety`tar -czf /root/backup.tar.gz /var/www
Cache recovery`wp cache flush

7. Comparison: && vs || vs ;​

OperatorExecution ConditionExampleBehavior
&&Runs second command only if first succeedscmd1 && cmd2Conditional success chaining
``Runs second command only if first fails
;Runs both commands regardlesscmd1 ; cmd2Sequential execution

8. Best Practices​

βœ… Use || for error handling or failover logic. βœ… Always combine with meaningful messages (e.g., echo, logger). βœ… When multiple fallbacks are possible, chain logically:

cmd1 || cmd2 || cmd3

βœ… Use parentheses for complex conditions:

(cmd1 && cmd2) || (echo "Either failed")

❌ Avoid mixing || with && without grouping β€” may cause unintended order. ❌ Don’t rely on visual order; always think in exit codes (0 = success).​

9. Quick Lab​

Goal: Test fallback logic and verify OR chaining behavior.

# Step 1: Run this (fail intentionally)
ls /fake/dir || echo "Fallback executed."

# Step 2: Create directory and test again
mkdir /tmp/testdir
ls /tmp/testdir || echo "This will not run."

# Step 3: Test multiple fallbacks
false || echo "First fallback" || echo "Second fallback"

Expected Outputs:

Fallback executed.
# (second test - no output)
First fallback


10. Troubleshooting Matrix​

ProblemCauseSolution
Command executes both sidesMisuse of ; instead of `
No fallback executedFirst command returns success (exit 0)Simulate failure to test
Unclear logic mixing && and ``
Script continues after failureNo exit condition usedAdd `

11. Cheat Sheet​

PatternPurposeExample
`cmd1cmd2`
`cmd1exit 1`
`(cmd1)(cmd2)`
`cmd1cmd2

12. Mini Quiz​

  1. What is the main function of || in Bash?
  2. What happens if cmd1 succeeds in cmd1 || cmd2?
  3. Which operator executes cmd2 only when cmd1 succeeds?
  4. Write a command that tries to restart Redis, or echoes a warning if it fails.
  5. How does cmd1 || cmd2 || cmd3 behave when all commands fail?