Skip to main content

📘 Command Grouping Using cmd1 | cmd2 (Pipe Operator)


1. What You Will Learn

  1. Understand the concept of piping between commands.
  2. Learn how cmd1 | cmd2 transfers standard output (stdout) from one command as standard input (stdin) to another.
  3. Explore real-world use in WordPress VPS tasks like searching logs, filtering processes, or analyzing WP-CLI outputs.
  4. Identify differences between pipes and redirection (>, <).
  5. Combine pipes with advanced text utilities like grep, awk, and sort for automation.
  6. Recognize common mistakes and performance caveats when chaining multiple pipes.

2. 5W + 1H Framework

ElementDescription
Whatis called the pipe operator. It’s one of the most powerful features in shell scripting — it allows chaining commands so that the output of the first command (cmd1) becomes the input of the second (cmd2).
WhyIt allows processing of large or filtered data streams without creating temporary files, making scripts more efficient.
WhoUseful for system administrators, DevOps engineers, and WordPress VPS maintainers who manage logs, monitor performance, and automate WP-CLI tasks.
WhereCommonly used in Linux shell pipelines, cron jobs, and real-time monitoring scripts.
WhenUsed when you need to filter, sort, or extract data from another command’s output.
HowBy joining commands with `

3. Core Syntax & Concept

The pipe operator (|) in Bash connects two or more commands so that the standard output (stdout) of the command on the left becomes the standard input (stdin) of the command on the right. You can think of it as building a data pipeline that flows through a sequence of filters.

3.1 Basic Syntax

cmd1 | cmd2

  • cmd1 produces output.
  • cmd2 reads that output as its own input. The pipe does not create any temporary files; everything is handled in memory, which makes it extremely fast and efficient.

Example 1 – Filtering Text

cat /var/log/syslog | grep "php-fpm"

Explanation: cat prints the contents of /var/log/syslog. The output stream is sent to grep, which filters only lines that contain "php-fpm". Expected Output Example

Oct 10 14:12:23 server php-fpm[1548]: pool wordpress
Oct 10 14:13:01 server php-fpm[1548]: request took 1.23s

Use Case: Monitoring PHP-FPM log events without manually opening large log files.

Example 2 – Chaining Multiple Commands

ps aux | grep php | sort -rk 3 | head -5

Explanation:

  1. ps aux lists all running processes.
  2. grep php filters only PHP-related processes.
  3. sort -rk 3 sorts by the 3rd column (CPU usage) in reverse order.
  4. head -5 displays the top 5 entries. Expected Output
root 1492 12.3 1.2 517284 24684 ? S 14:10 0:03 php-fpm: pool www
www-data 1520 10.5 0.9 505684 18512 ? S 14:10 0:02 php-fpm: pool www
...

Use Case: Quickly check which PHP processes are consuming the most CPU on a VPS running WordPress.

Example 3 – WordPress Automation via WP-CLI

wp plugin list --allow-root | grep active

Explanation: wp plugin list prints all plugins with their status. grep active filters only the lines showing active plugins. Expected Output

akismet active
litespeed-cache active
woocommerce active

Use Case: Auditing active plugins across multiple WordPress sites during maintenance.

Example 4 – Sorting Disk Usage

du -h /var/www | sort -hr | head -10

Explanation: du -h displays human-readable folder sizes. sort -hr sorts them from largest to smallest. head -10 shows only the top 10 entries. Expected Output

3.4G /var/www/site1
2.1G /var/www/site2
...

Use Case: Identify the heaviest websites or upload directories on the server.

Example 5 – Extracting Specific Columns

ls -lh /home | awk '{print $9, $5}'

Explanation: ls -lh lists files with human-readable sizes. awk prints only the file name ($9) and size ($5). Expected Output

wordpress 1.2G
metaxenith 950M
devwp 310M

Use Case: Generate a concise overview of directory sizes for capacity planning.

Example 6 — Filter Output

ls -l | grep ".txt"

Explanation:

  • ls -l lists files in long format.
  • The output is piped (|) into grep ".txt".
  • grep filters only lines containing .txt. Expected Output:
-rw-r--r-- 1 root root 824 Oct 12 notes.txt
-rw-r--r-- 1 root root 192 Oct 12 todo.txt


Example 7 — Count Processed Lines

ps aux | wc -l

Explanation:

  • ps aux lists all running processes.
  • wc -l counts the number of lines.
  • The result shows how many processes are running. Expected Output:
127


Example 8 — Combining Tools (WordPress Server Context)

wp plugin list --allow-root | grep "active"

Explanation:

  • wp plugin list lists all plugins in the current WordPress site.
  • grep "active" filters only the active ones. Expected Output:
akismet active
litespeed-cache active
perfmatters active



4. Practical Use Cases

Use CaseCommand ExampleExpected Output
Filter PHP errors from logs`cat /var/log/sysloggrep php`
Find heavy processes`ps auxsort -rk 3
Check active plugins in WordPress`wp plugin list --allow-rootgrep active`
Count active PHP-FPM workers`ps auxgrep php-fpm
Analyze web access frequency`cat access.logawk '{print $1}'
Find largest uploads`du -h /home/user/uploadssort -hr
Monitor WordPress cron jobs`wp cron event list --allow-rootgrep publish`

5. Benefits

CategoryDescription
EfficiencyNo temporary files – uses data streams directly.
ComposabilitySmall commands can be combined into powerful pipelines.
AutomationPerfect for cron jobs and WordPress maintenance scripts.
ReadabilityEasier to follow logical flow than nested commands.

6. Implementation Steps

  1. Identify the main command that produces data (e.g., wp, ps, cat).
  2. Decide which filter command should process the output (grep, awk, sort, etc.).
  3. Connect them using the pipe (|) operator.
  4. Test the pipeline interactively in the terminal.
  5. Embed successful pipelines into automation scripts or aliases.

7. Best Practices

PracticeDescription
Use simple, single-purpose commandsEasier debugging and maintenance.
Keep pipes short (≤ 3 stages)Avoid performance overhead.
Combine with redirection (> logfile.txt) for persistent logsUseful for auditing.
Use quotes for complex patternsPrevents shell misinterpretation.
Validate output after each pipeDetect broken commands in sequence.

8. Static vs Dynamic Framing (WordPress Context)

TypeExampleBehavior
Static`cat /var/log/sysloggrep "php"`
Dynamic`wp plugin listgrep active`

9. Go-Live Checklist

  1. Verify each command individually before piping.
  2. Escape special characters when using regex filters.
  3. Log pipeline output when used in cron or long scripts.
  4. Use tee when you need both screen and file output. Example:
wp plugin list --allow-root | tee /root/plugin-status.log | grep active


10. Troubleshooting Matrix

SymptomPossible CauseSolution
No output shownUpstream command produces no stdoutRun cmd1 alone to test output.
“Broken pipe” errorReceiving command exits earlyValidate data format and command compatibility.
Unexpected extra linesCommand includes stderrUse 2>/dev/null to suppress errors.
Permission deniedwp or log file requires root accessAdd --allow-root or adjust permission.

11. Quick Lab

Task: Filter all active plugins on all WordPress sites hosted under /home.

for site in /home/*/*/public_html; do
echo "Checking: $site"
wp plugin list --path="$site" --allow-root | grep active
echo "-----------------------------------"
done

Expected Output:

Checking: /home/site1/public_html
akismet active
litespeed-cache active
-----------------------------------
Checking: /home/site2/public_html
woocommerce active
-----------------------------------


12. Cheat Sheet

OperatorDescriptionExample
``Pipe output of one command as input to another
`tee file`Save and display output simultaneously
`wc -l`Count number of lines
`sort -r`Reverse-sort output
`uniq -c`Count unique occurrences

13. Mini-Quiz

#QuestionAnswer
1What does the pipe (``) operator do?
2How is a pipe different from > redirection?Pipe transfers output between commands, not to a file.
3Can you use multiple pipes in a single line?Yes, e.g., `cmd1
4How to view both screen output and save to file simultaneously?Use tee, e.g., `cmd
5What happens if the first command has no stdout?The next command receives no input, so no output.