Skip to main content

πŸ“˜ Standard Streams



🎯 What You Will Learn​

  1. Understand the three standard streams in Bash: input, output, and error.
  2. Learn how Bash commands communicate through file descriptors (0, 1, 2).
  3. Differentiate between stdout, stderr, and stdin clearly.
  4. Redirect streams using operators like >, <, 2>, and &>.
  5. Apply stream management to WordPress automation, logging, and safe error capture.
  6. Implement output filtering for CLI commands like wp, tar, and grep.

1. 5W + 1H Framework​

ElementDescription
WhatStandard streams are the default communication channels between a process and the terminal β€” input, output, and error.
WhyThey allow command results, logs, and errors to be separated, redirected, or combined for automation safety.
WhoBash users, WordPress admins, and DevOps engineers managing scripts and cron jobs.
WhereEverywhere in Linux and Bash scripting (CLI tools, system daemons, or cron jobs).
WhenWhen automating WP-CLI commands, capturing logs, or redirecting data safely to files.
HowFile descriptors 0, 1, and 2 correspond to stdin, stdout, and stderr, respectively, and can be controlled with redirection operators.

2. Prerequisites​

  • Completed Module 3.5 (Parameter Expansion).
  • Basic familiarity with executing scripts and viewing terminal output.
  • Understanding of Linux file paths and permissions.

3. Core Syntax & Concept (Revised and Verified)​

NoSyntax FormulaType Syntax ExampleDescriptionBehavior / Output
10Standard Input (stdin)cat 0< file.txtReads data into a command from a file via descriptor 0. Equivalent to cat < file.txt.Displays contents of file.txt on screen.
21Standard Output (stdout)echo "Hello" 1> out.txtRedirects output (descriptor 1) to a file instead of screen.Creates out.txt containing β€œHello”.
32Standard Error (stderr)ls /root 2> error.logRedirects error messages (descriptor 2) to error.log.Captures permission-denied messages.
4>Redirect stdout (overwrite)wp plugin list > plugins.txtRedirects normal output to file (replaces existing).Saves plugin list.
5>>Append stdoutecho "Backup done" >> log.txtAppends output to an existing file.Adds β€œBackup done” at end.
6<Redirect stdinsort < unsorted.txtReads file as input instead of keyboard.Outputs sorted content.
72>Redirect stderrtar -czf backup.tar.gz /missing 2> err.logCaptures error messages only.Errors go to file.
82>>Append stderrgrep TODO *.sh 2>> error.logAppends errors (like missing files) to log.Keeps previous logs.
9&>Redirect stdout + stderrwp plugin update --all &> update.logCombines both output and errors into one file.Unified log.
101>Explicit stdout redirectls /etc 1> list.txtSame as > β€” explicit descriptor version.Creates list.txt.
111>>Explicit append stdoutdate 1>> system.logAppends timestamp to log file.Adds line at end.
122>&1Merge stderr β†’ stdout`wp core update 2>&1tee update.log`Combines stderr into stdout before piping.
13/dev/nullNull device (discard)command > /dev/null 2>&1Discards both output and errors silently.Used in cron jobs.
14execRedirect whole scriptexec > script.log 2>&1Redirects all future output to a log file.Persistent log.
15read varCapture stdin into variableread user; echo "Hi $user"Reads user input interactively.Displays greeting.
16teeSplit output stream`lstee files.txt`Displays and writes output simultaneously.
17>&2Manual stderr redirectionecho "Error: Invalid path" >&2Sends custom message to stderr.Helpful for logging errors.
18< input > outputDual redirectionsort < names.txt > sorted.txtReads from one file, writes to another.Sorted file created.

4. Demonstration Example​

Input Script:

#!/bin/bash
wp plugin list 1> plugins.log 2> errors.log
echo "Logs written successfully."

Expected Output:

Logs written successfully.

File Output:

  • plugins.log β†’ plugin list (stdout)
  • errors.log β†’ errors (stderr) Explanation: Here, 1> explicitly redirects normal output, while 2> redirects errors. Bash automatically uses these file descriptors.

5. Use Cases (WordPress-VPS Focused)​

5.1 (Ref: #2) – Save Plugin List to File​

wp plugin list 1> /var/log/wp_plugins.log

Use Case: Audit plugin lists automatically.​

5.2 (Ref: #3) – Capture Backup Errors​

tar -czf /home/wpbackup/backup.tar.gz /wrong/path 2> /var/log/backup_error.log

Output: (silent) Explanation: Errors stored separately for debugging.​

5.3 (Ref: #9) – Combine Output and Errors​

wp plugin update --all &> /var/log/wp_update.log

Use Case: Single log file for automation summary.​

5.4 (Ref: #13) – Quiet Cron Jobs​

wp transient delete --expired > /dev/null 2>&1

Use Case: Suppress unwanted cron job output.​

5.5 (Ref: #12) – Log While Viewing​

wp core update 2>&1 | tee /var/log/wp_core_update.log

Output:

Success: WordPress updated successfully.

Explanation: Displays progress and records logs simultaneously.​

5.6 (Ref: #14) – Redirect Full Script to Log​

#!/bin/bash
exec > /var/log/wp_daily.log 2>&1
echo "Starting daily maintenance..."
wp plugin update --all
wp theme update --all
echo "Completed at $(date)"

Output (terminal): (none) File: /var/log/wp_daily.log​

5.7 (Ref: #17) – Manual Error Reporting​

if [ ! -d "/var/www/html" ]; then
echo "❌ WordPress directory not found!" >&2
fi

Output:

❌ WordPress directory not found!


5.8 (Ref: #16) – Mirror Output to Log​

wp cache flush | tee -a /var/log/wp_cache.log

Output:

Success: Object cache flushed.


6. Best Practices​

PracticeDescription
Use file descriptors explicitly (1>, 2>)Improves script readability.
Separate logs for stdout and stderrSimplifies debugging.
Always use >> for long-term logsAvoids overwriting.
Use /dev/null sparinglyDon’t lose critical output.
Prefer tee for monitoringEnables real-time feedback.
Write intentional errors to >&2Distinguishes between normal and failure output.

7. Common Mistakes & Fixes​

MistakeWrong ExampleCorrect ExampleExplanation
Missing error redirectioncommand > log.txtcommand 1> log.txt 2> err.txtErrors remain visible.
Overwriting logs> used repeatedlyUse >>Appends logs safely.
Reversed merge order2>&1 > file> file 2>&1Must redirect stdout first.
Unquoted pathsecho >> /path with space/file.txtecho >> "/path with space/file.txt"Prevents word splitting.
Losing old logs with tee`commandtee file``command

8. Quick Lab – Unified WordPress Update Logger​

Script: wp_update_log.sh

#!/bin/bash
# --------------------------------------------
# Script Name : wp_update_log.sh
# Purpose : Log both output and errors during WordPress update
# --------------------------------------------

LOG="/var/log/wp_update_$(date +%F).log"

wp plugin update --all 1>> "$LOG" 2>&1
wp theme update --all 1>> "$LOG" 2>&1

echo "βœ… Updates logged to $LOG"

Expected Output:

βœ… Updates logged to /var/log/wp_update_2025-10-09.log


9. Troubleshooting Matrix​

IssueSymptomCauseSolution
Log emptyNothing recordedWrong redirection orderUse > file 2>&1.
Old logs missingOverwrittenUse >> for append.
Errors shownstderr not redirectedAdd 2> file.
Cron job silentOverused /dev/nullTest before silencing output.

10. Static vs Dynamic Framing​

FramingDescriptionBehavior
StaticFixed file paths for logging.Predictable but rigid.
DynamicUses variables or timestamps.Flexible and self-documenting.

11. Cheat Sheet​

TaskSyntax / Example
Redirect stdin0< file.txt
Redirect stdout1> file.txt
Redirect stderr2> error.txt
Redirect both&> all.log
Merge stderr β†’ stdout2>&1
Discard all> /dev/null 2>&1
Split output`command
Global redirectexec > logfile.txt 2>&1
Manual errorecho "Error" >&2

12. Mini-Quiz​

#QuestionAnswer
1Which file descriptor represents stdin?0
2Which descriptor handles normal output?1
3Which redirects errors only?2>
4How to merge stdout and stderr?2>&1
5Which operator discards all output?/dev/null