Skip to main content

Module 2.2 – Command Chaining



🎯 What You Will Learn

  1. Understand what command chaining means in Bash scripting.
  2. Learn how to use the chaining operators ;, &&, and || effectively.
  3. Differentiate between sequential, conditional, and logical chaining.
  4. Combine commands efficiently to automate multi-step WordPress server tasks.
  5. Apply chaining with exit statuses for advanced scripting control.
  6. Avoid common pitfalls such as unintended command execution or missing error checks.

1. 5W + 1H Framework

ElementDescription
WhatCommand chaining lets you link multiple commands on a single line, controlling how the next command executes based on the success or failure of the previous one.
WhyReduces script size, improves readability, and adds conditional flow without full if statements.
WhoUseful for DevOps engineers, sysadmins, or WordPress managers automating shell operations.
WhereWithin Bash scripts or directly in terminal sessions.
WhenWhen you need to run tasks sequentially or stop execution upon failure.
HowUse chaining operators like ;, &&, and `

2. Prerequisites

  • Familiarity with Bash syntax and execution permissions (chmod +x).
  • Basic knowledge of exit status codes (0 = success, non-zero = failure).
  • Understanding of WordPress server tasks and automation.

3. Core Structure: Chaining Operators Overview

OperatorNameExecution BehaviorExampleDescription
;SequentialExecutes commands one after another, regardless of success or failure.cmd1; cmd2Always runs both commands.
&&AND (Conditional)Executes the next command only if the previous one succeeded (exit code 0).cmd1 && cmd2Runs cmd2 only if cmd1 succeeded.
``OR (Alternative)Executes the next command only if the previous one failed (non-zero exit code).

4. Basic Syntax and Output

4.1 Using ; – Sequential Execution

echo "Updating system..."; apt update; echo "Done."

Expected Output:

Updating system...
Hit:1 http://archive.ubuntu.com/ubuntu ...
Done.

Even if one command fails, Bash continues executing the rest.

4.2 Using && – Conditional Success

mkdir /home/backup && echo "Backup directory created successfully."

Expected Output:

Backup directory created successfully.

If the directory already exists (error), the echo command will not run.

4.3 Using || – Conditional Failure

mkdir /home/backup || echo "Backup directory already exists."

Expected Output:

Backup directory already exists.

If mkdir fails, the echo command is executed as a fallback.

5. Combining Operators

You can chain multiple operators in one line.

systemctl restart lsws && echo "Server restarted successfully" || echo "Server restart failed"

Logic Explanation:

  1. If restart succeeds → print “Server restarted successfully.”
  2. If restart fails → print “Server restart failed.” Expected Output (success case):
Server restarted successfully

Expected Output (failure case):

Server restart failed


6. Practical Examples for WordPress VPS

Use CaseCommand ExampleDescription
Backup and Cleantar -czf /home/backup/wp.tar.gz /var/www/html && rm -rf /tmp/cacheCompress WordPress directory, then clear cache if backup succeeded.
Update & Restart OLSwp plugin update --all && systemctl reload lswsUpdates all plugins; reloads web server only if successful.
Database Export Fallback`wp db export /home/backup/db.sql
Sequential Tasksapt update; apt upgrade -y; systemctl restart lswsRun three maintenance commands in sequence regardless of success.
Conditional Chain`[ -f /etc/lsws/httpd_config.conf ] && echo "Config exists"

7. Combining with Subshells and Grouping

You can combine grouping ({} or ()) with chaining for cleaner logic:

{ wp plugin update --all && wp theme update --all; } || echo "Update failed"

Expected Output (if success):

Success: Updated all plugins.
Success: Updated all themes.

If one fails:

Update failed


8. Using Exit Codes for Control Flow

You can check the exit code of the previous command using $?.

wp db export /home/backup/db.sql
if [ $? -eq 0 ]; then
echo "Database exported successfully."
else
echo "Database export failed."
fi

Short equivalent using chaining:

wp db export /home/backup/db.sql && echo "Success" || echo "Fail"


9. Static vs Dynamic Framing

TypeDescriptionBehavior
Static (Sequential)Uses ; — always runs all commands.Ideal for linear workflows.
Dynamic (Conditional)Uses && and `

10. Troubleshooting Matrix

IssueSymptomCauseSolution
Unexpected command executionBoth success and failure messages printedWrong operator combinationUse && and `
Command stops too earlyChain breaks on error&& stops when first failsUse ; for sequential execution
Missing spacesSyntax error near unexpected tokenNo space between operatorsAlways use spaces: cmd1 && cmd2
Cron chain failsWorks manually but not in cronPATH differencesUse full command paths (e.g., /usr/bin/wp)

11. Quick Lab – WordPress Maintenance Chain

Script: wp_maintenance.sh

#!/bin/bash
echo "Starting maintenance..."
wp plugin update --all --path=/var/www/html && \
wp theme update --all --path=/var/www/html && \
wp core update --path=/var/www/html && \
echo "All updates completed successfully" || \
echo "One or more updates failed"

Run:

chmod +x wp_maintenance.sh
./wp_maintenance.sh

Expected Output (success):

Success: Updated all plugins.
Success: Updated all themes.
Success: WordPress updated successfully.
All updates completed successfully

Expected Output (failure):

Error: Connection timeout.
One or more updates failed


12. Cheat Sheet

OperatorDescriptionExample
;Run sequentially regardless of resultcmd1; cmd2
&&Run next only if previous succeededcmd1 && cmd2
``
Combine && + ``
Test command exit code$?echo $?

13. Mini-Quiz

#QuestionAnswer
1Which operator runs commands sequentially regardless of success?;
2Which operator runs the next command only on success?&&
3Which operator runs the next command only on failure?`
4What does $? represent?The exit status of the previous command.
5Why prefer && over ; in automation?It ensures dependent tasks only run if prior ones succeed.