Skip to main content

πŸ“˜ Command Grouping Using cmd1 |& cmd2 (Pipe stdout and stderr)


1. What You Will Learn​

  1. Understand how the |& operator works in Bash to send both stdout and stderr to another command.
  2. Learn how it differs from the regular pipe (|) which only sends stdout.
  3. Apply |& to handle error logs and outputs together in pipelines.
  4. Use |& for debugging WordPress scripts, service commands, or complex CLI loops.
  5. Learn best practices and compatibility notes for using |& in Bash 4+ environments.
  6. Recognize practical examples combining |& with grep, tee, or awk.

2. 5W + 1H Framework​

ElementDescription
WhatThe `
WhyTo capture and process all messagesβ€”both normal and errorβ€”in a single unified stream, especially useful in automation and debugging.
WhoIdeal for system administrators, DevOps engineers, and WordPress VPS managers who need to analyze combined command output for troubleshooting.
WhereCommonly used in Bash scripts, cron jobs, and diagnostic automation on Linux servers.
WhenUsed when you need to process or log both successful and error messages through the same pipeline.
HowBy joining commands using `

3. Core Syntax & Concept​

The |&** operator** is a Bash shortcut that sends both stdout and stderr from the first command into the stdin of the second command. It behaves like a regular pipe (|) but merges error messages into the same stream.

3.1 Basic Syntax​

cmd1 |& cmd2

Equivalent to:

cmd1 2>&1 | cmd2

Explanation:

  • stdout (file descriptor 1) and stderr (file descriptor 2) from cmd1 are both redirected into the pipeline.
  • cmd2 receives all combined output.

3.2 Example 1 – Capturing Errors and Output Together​

ls /nonexistent /etc |& grep "No such"

Explanation: The command ls /nonexistent /etc produces an error message because the first directory does not exist. Using |& ensures that both standard and error outputs are passed to grep. Expected Output:

ls: cannot access '/nonexistent': No such file or directory

Use Case: Quickly filter and view specific error messages from a command without losing them.​

3.3 Example 2 – Debugging a WordPress Command​

wp plugin update --all --allow-root |& tee /root/wp-update.log

Explanation:

  • wp plugin update --all updates all plugins.
  • Both successful updates and error messages are piped to tee, which saves the output to /root/wp-update.log and displays it on screen. Expected Output (Partial):
Updating Akismet (4.2.1 β†’ 4.2.2)
Success: Updated 1 of 1 plugins.
Warning: Unable to update litespeed-cache (connection timeout)

Use Case: Debugging automated WordPress maintenance scripts that occasionally produce network or timeout errors.​

3.4 Example 3 – Merging Logs for Analysis​

( wp plugin list --allow-root; wp theme list --allow-root ) |& grep active

Explanation: This runs two WordPress CLI commands, merging their outputs and errors into a single stream. grep active filters only the active items. Expected Output:

akismet active
litespeed-cache active
twentytwentyfour active

Use Case: Analyze multiple types of WordPress data (plugin/theme) with unified output and consistent formatting.​

3.5 Example 4 – Checking System Resource Errors​

df -h /mnt |& grep "No such"

Explanation: If /mnt is unavailable, the error message is piped directly to grep. No need for separate redirection (2>&1). Expected Output:

df: /mnt: No such file or directory

Use Case: Simplify file system checks or scheduled cron validation.​

3.6 Concept Summary​

  1. The pipe | passes stdout only.
  2. The pipe |& passes stdout + stderr together.
  3. |& is shorthand for 2>&1 |.
  4. It works only in Bash 4.0+, not POSIX sh.
  5. Very effective for debugging, automation logs, and combined reporting.
  6. Ideal when working with unpredictable scripts that may produce errors (e.g., during WordPress updates, database imports, or network operations).

4. Practical Use Cases​

Use CaseCommand ExampleExpected Output
Capture all plugin update logs`wp plugin update --all& tee /root/wp.log`
Check missing PHP extensions`php -m& grep -i missing`
Log MySQL import output`mysql -u root -p dbname < file.sql& tee import.log`
Monitor Redis status`redis-cli info& grep connected_clients`
Test connection to WP-CLI`wp core is-installed --allow-root& grep Error`

5. Benefits​

CategoryDescription
Unified OutputCombines stdout and stderr for full visibility.
Easier DebuggingHelps diagnose issues without losing error messages.
Clean LoggingSingle output stream simplifies automation logs.
EfficiencyAvoids creating separate redirection lines like 2>&1.
CompatibilityCleaner Bash syntax for advanced users.

6. Implementation Steps​

  1. Identify a command that may generate both output and error messages.
  2. Replace the regular pipe | with |&.
  3. Pipe the result into a processor like grep, awk, or tee.
  4. Run the command and verify that both stdout and stderr appear.
  5. Optionally, save or filter the combined output as needed.

7. Best Practices​

PracticeDescription
Always use `&` for mixed-output scripts
Use tee to log output and still see it liveExample: `cmd
Combine with timestamped logsExample: `cmd
Avoid unnecessary pipingUse `
Validate Bash versionWorks on Bash 4.0+ (run bash --version to confirm).

8. Static vs Dynamic Framing (WordPress Context)​

TypeExampleBehavior
Static`ls /nonexistent& grep "No such"`
Dynamic`wp plugin update --all& tee update.log`

9. Go-Live Checklist​

  1. Confirm your Bash version supports |& (4.0 or higher).
  2. Test your command manually before embedding in cron or scripts.
  3. Use tee for persistent logs when running automation.
  4. Include error checks (grep Error) for validation in pipelines.
  5. If backward compatibility is needed, use 2>&1 | instead.

10. Troubleshooting Matrix​

SymptomPossible CauseSolution
β€œcommand not found” errorUsing `&` in a non-Bash shell
Missing error messagesCommand outputs only to stderrConfirm `
Empty log fileCommand produced no outputVerify command actually generates stdout or stderr.
Broken pipelineCommand terminates earlyTest each stage independently.

11. Quick Lab​

Task: Capture both normal and error outputs when checking all WordPress sites for broken configurations.

for site in /home/*/*/public_html; do
echo "Checking: $site"
( wp core is-installed --path="$site" --allow-root; wp plugin list --allow-root --path="$site" ) |& tee -a /root/wp-check.log
echo "-----------------------------------"
done

Expected Output (Partial):

Checking: /home/metaxenith/public_html
Success: WordPress is installed.
akismet active
litespeed-cache active
-----------------------------------
Checking: /home/devwp/public_html
Error: This does not seem to be a WordPress installation.
-----------------------------------


12. Cheat Sheet​

OperatorMeaningExample
``Pipe only stdout
`&`Pipe stdout and stderr
`2>&1`Traditional equivalent of `
`& tee file`Log all outputs
`& grep`Filter combined output

13. Mini-Quiz​

#QuestionAnswer
1What is the purpose of `&` in Bash?
2What is `cmd1& cmd2` equivalent to?
3Does `&work in POSIXsh`?
4How do you log and view output simultaneously?Use `cmd
5Why is `&` useful for automation?

Would you like the next topic to continue with Module 2.1.f – Combining Multiple Pipes (cmd1 | cmd2 |& cmd3), which merges selective stderr redirection within longer command pipelines?