📘 **Command Chaining using **cmd1 && cmd2
🎯 What You Will Learn
- Understand the concept of command chaining using
&&in Bash. - Learn how to execute multiple commands conditionally — only when the first succeeds.
- Explore execution flow and exit status logic behind
&&. - Apply command chaining for automation, WordPress VPS management, and system maintenance.
- Identify and correct common mistakes when chaining commands.
- Implement practical use cases and test them directly on your VPS.
1. 5W + 1H Framework
| Element | Description |
| 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). |
| Why | To create reliable automation where failure in one step prevents the next from executing — e.g., avoiding corrupt deployments or partial updates. |
| Who | System administrators, DevOps engineers, and WordPress VPS managers. |
| When | When you need to execute dependent commands that should only run on success (e.g., database backups, updates, deployments). |
| Where | Within Bash CLI, shell scripts, or aliases for automation (like updating all plugins, restarting PHP-FPM, etc.). |
| How | By 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 Formula | Syntax Example | Description |
| 0 | command1 && command2 | apt update && apt upgrade -y | Runs command2 only if command1 exits successfully (0). |
| 1 | cmd1 && cmd2 && cmd3 | cd /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. |
| 3 | cmd1 && { cmd2; cmd3; } | cd /var/www/html && { ls; pwd; } | Combines logical AND with a command group using {}. |
| 4 | cmd1 && echo "Success" | systemctl restart redis && echo "Redis restarted successfully" | Runs a message or follow-up task if the first command succeeds. |
| 5 | `cmd1 && cmd2 | cmd3` |
4. Conceptual Flow
# Example 1
mkdir /root/test && echo "Directory created successfully"
Expected Output:
Directory created successfully
Explanation:
- The
echocommand runs only ifmkdir /root/testexecutes without error. - If
/root/testalready exists,mkdirfails →echois skipped.
# Example 2
cd /var/www/html && ls
Expected Output:
index.php
wp-content
wp-includes
wp-admin
...
Explanation:
lsexecutes 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 lswsruns only if plugin updates succeed.echoconfirms the final completion.
5. Use Cases in WordPress VPS
| Scenario | Example Command | Description |
| 1. Update System Packages | apt update && apt upgrade -y && apt autoremove -y | Ensures packages are updated only if the previous step succeeds. |
| 2. Plugin & Theme Updates | wp plugin update --all && wp theme update --all | Update themes only if plugins update successfully. |
| 3. Cache & Restart Services | redis-cli flushall && systemctl restart redis && echo "Redis cache cleared!" | Flush cache and restart service conditionally. |
| 4. Backup & Compress Database | mysqldump -u root -p wpdb > /root/backup.sql && gzip /root/backup.sql | Compress backup only if dump creation succeeds. |
| 5. Deployment Automation | git pull && composer install && npm run build | Ensures each build step runs only on success of the previous. |
| 6. Safe Restart Sequence | systemctl restart php8.3-fpm && systemctl restart lsws | Avoids restarting web server if PHP fails to restart. |
6. Best Practices
| Practice | Description |
✅ Use && for dependent tasks only | Avoid chaining unrelated commands. |
| ✅ Include logging | Example: cmd1 && echo "$(date): Success" >> /var/log/script.log |
| ✅ **Combine with ` | |
| ✅ Use meaningful messages | Always provide clear feedback after successful commands. |
| ⚠️ Avoid chaining destructive commands | Never do rm -rf /var/www/html && rm -rf /home/user. |
| ⚙️ Test interactively before automation | Always test manually before adding to cron or script. |
7. Common Mistakes & Fixes
| Mistake | Example | Problem | Fix |
| Missing space | cmd1&&cmd2 | Works but hard to read | Use cmd1 && cmd2 |
| Wrong chaining logic | cmd1; cmd2 | Runs both regardless of failure | Use && for conditional execution |
| Ignoring exit codes | cmd1 && cmd2 | May skip cmd2 if cmd1 fails | Check $? to debug |
| Using sudo incorrectly | sudo cmd1 && cmd2 | cmd2 may run as non-root | Apply sudo consistently where needed |
8. Troubleshooting Matrix
| Issue | Cause | Solution |
| Second command not running | First command failed | Run echo $? to check exit status. |
| Unexpected behavior in script | Improper syntax or quotes | Use bash -x script.sh to debug. |
| Commands run even on failure | Used ; instead of && | Replace ; with &&. |
| Permission denied | Insufficient privileges | Prefix 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
| Pattern | Meaning | Example |
cmd1 && cmd2 | Run cmd2 if cmd1 succeeds | ls && pwd |
cmd1 && cmd2 && cmd3 | Chain 3+ success-dependent commands | apt update && apt upgrade -y && reboot |
cmd1 && echo "OK" | Print success message only on success | redis-cli ping && echo "Redis OK" |
| `cmd1 && cmd2 | cmd3` |
11. Mini-Quiz
- What happens if the first command in
cmd1 && cmd2fails? → The second command will not execute. - How does
&&differ from;? →;runs all commands regardless of result, while&&depends on success. - What exit code value represents success?
→
0. - Which chain restarts Redis only if cache flush is successful?
→
redis-cli flushall && systemctl restart redis. - What’s the output of
false && echo "Run"? → Nothing —echois skipped.
Would you like me to continue this with cmd1 || cmd2** (logical OR chaining)** next — to complement this lesson in your Bash curriculum?