Skip to main content

📘 **Command Chaining using **cmd1 && cmd2



🎯 What You Will Learn

  1. Understand the concept of command chaining using && in Bash.
  2. Learn how to execute multiple commands conditionally — only when the first succeeds.
  3. Explore execution flow and exit status logic behind &&.
  4. Apply command chaining for automation, WordPress VPS management, and system maintenance.
  5. Identify and correct common mistakes when chaining commands.
  6. Implement practical use cases and test them directly on your VPS.

1. 5W + 1H Framework

ElementDescription
What&& is a logical AND operator in Bash used to chain two or more commands, where each subsequent command runs only if the previous one succeeds (exit status 0).
WhyTo create reliable automation where failure in one step prevents the next from executing — e.g., avoiding corrupt deployments or partial updates.
WhoSystem administrators, DevOps engineers, and WordPress VPS managers.
WhenWhen you need to execute dependent commands that should only run on success (e.g., database backups, updates, deployments).
WhereWithin Bash CLI, shell scripts, or aliases for automation (like updating all plugins, restarting PHP-FPM, etc.).
HowBy linking multiple commands with &&, forming a conditional execution chain. Example: cmd1 && cmd2 && cmd3

2. Prerequisites

  • Basic knowledge of:
  • Bash command-line environment.
  • Command exit status codes ($?).
  • Understanding of the difference between sequential (;) and conditional (&&) execution.
  • Access to a Linux VPS or local terminal.

3. Core Syntax & Concept

No.Syntax FormulaSyntax ExampleDescription
0command1 && command2apt update && apt upgrade -yRuns command2 only if command1 exits successfully (0).
1cmd1 && cmd2 && cmd3cd /var/www/html && ls && echo "Listed successfully"Chains multiple commands — each runs only if the previous succeeds.
2(cmd1 && cmd2)(cd /home && mkdir testdir)Groups chained commands in a subshell.
3cmd1 && { cmd2; cmd3; }cd /var/www/html && { ls; pwd; }Combines logical AND with a command group using {}.
4cmd1 && echo "Success"systemctl restart redis && echo "Redis restarted successfully"Runs a message or follow-up task if the first command succeeds.
5`cmd1 && cmd2cmd3`

4. Conceptual Flow

# Example 1
mkdir /root/test && echo "Directory created successfully"

Expected Output:

Directory created successfully

Explanation:

  • The echo command runs only if mkdir /root/test executes without error.
  • If /root/test already exists, mkdir fails → echo is skipped.

# Example 2
cd /var/www/html && ls

Expected Output:

index.php
wp-content
wp-includes
wp-admin
...

Explanation:

  • ls executes only if the directory change (cd) is successful.
  • Prevents listing a directory that doesn't exist.

# Example 3 (WordPress Automation)
wp plugin update --all && systemctl restart lsws && echo "All plugins updated and LSWS restarted"

Expected Output:

Success: Updated 12 of 12 plugins.
All plugins updated and LSWS restarted

Explanation:

  • systemctl restart lsws runs only if plugin updates succeed.
  • echo confirms the final completion.

5. Use Cases in WordPress VPS

ScenarioExample CommandDescription
1. Update System Packagesapt update && apt upgrade -y && apt autoremove -yEnsures packages are updated only if the previous step succeeds.
2. Plugin & Theme Updateswp plugin update --all && wp theme update --allUpdate themes only if plugins update successfully.
3. Cache & Restart Servicesredis-cli flushall && systemctl restart redis && echo "Redis cache cleared!"Flush cache and restart service conditionally.
4. Backup & Compress Databasemysqldump -u root -p wpdb > /root/backup.sql && gzip /root/backup.sqlCompress backup only if dump creation succeeds.
5. Deployment Automationgit pull && composer install && npm run buildEnsures each build step runs only on success of the previous.
6. Safe Restart Sequencesystemctl restart php8.3-fpm && systemctl restart lswsAvoids restarting web server if PHP fails to restart.

6. Best Practices

PracticeDescription
Use && for dependent tasks onlyAvoid chaining unrelated commands.
Include loggingExample: cmd1 && echo "$(date): Success" >> /var/log/script.log
✅ **Combine with `
Use meaningful messagesAlways provide clear feedback after successful commands.
⚠️ Avoid chaining destructive commandsNever do rm -rf /var/www/html && rm -rf /home/user.
⚙️ Test interactively before automationAlways test manually before adding to cron or script.

7. Common Mistakes & Fixes

MistakeExampleProblemFix
Missing spacecmd1&&cmd2Works but hard to readUse cmd1 && cmd2
Wrong chaining logiccmd1; cmd2Runs both regardless of failureUse && for conditional execution
Ignoring exit codescmd1 && cmd2May skip cmd2 if cmd1 failsCheck $? to debug
Using sudo incorrectlysudo cmd1 && cmd2cmd2 may run as non-rootApply sudo consistently where needed

8. Troubleshooting Matrix

IssueCauseSolution
Second command not runningFirst command failedRun echo $? to check exit status.
Unexpected behavior in scriptImproper syntax or quotesUse bash -x script.sh to debug.
Commands run even on failureUsed ; instead of &&Replace ; with &&.
Permission deniedInsufficient privilegesPrefix with sudo or adjust file permissions.

9. Quick Lab: Practice on VPS

Objective: Update WordPress plugins and restart OpenLiteSpeed conditionally.

wp plugin update --all --allow-root && systemctl restart lsws && echo "✅ WP Plugins updated and LSWS restarted successfully."

Expected Output:

Success: Updated 8 of 8 plugins.
✅ WP Plugins updated and LSWS restarted successfully.

Now simulate failure:

wp plugin update --path=/wrong/path && echo "Done"

Expected Output:

Error: This does not seem to be a WordPress installation.

(→ The echo is not executed.)

10. Cheat Sheet

PatternMeaningExample
cmd1 && cmd2Run cmd2 if cmd1 succeedsls && pwd
cmd1 && cmd2 && cmd3Chain 3+ success-dependent commandsapt update && apt upgrade -y && reboot
cmd1 && echo "OK"Print success message only on successredis-cli ping && echo "Redis OK"
`cmd1 && cmd2cmd3`

11. Mini-Quiz

  1. What happens if the first command in cmd1 && cmd2 fails? The second command will not execute.
  2. How does && differ from ;? ; runs all commands regardless of result, while && depends on success.
  3. What exit code value represents success? 0.
  4. Which chain restarts Redis only if cache flush is successful? redis-cli flushall && systemctl restart redis.
  5. What’s the output of false && echo "Run"? Nothing — echo is skipped.

Would you like me to continue this with cmd1 || cmd2** (logical OR chaining)** next — to complement this lesson in your Bash curriculum?