Understanding Linux Standard Streams - stdin, stdout, and stderr

A comprehensive guide to Linux standard streams and redirection

Featured image



Overview

Linux standard streams (stdin, stdout, and stderr) are fundamental channels for managing input and output in terminal or command-line interfaces.


Standard Input (stdin)

File Descriptor: 0
Default Source: Keyboard
Purpose: Receives input for commands

Examples

# Basic stdin usage
cat    # Waits for keyboard input

# Redirect file to stdin
cat < file.txt

Standard Output (stdout)

File Descriptor: 1
Default Destination: Terminal screen
Purpose: Displays command output

Examples

# Basic stdout usage
echo "Hello, World!"

# Redirect stdout to file
echo "Hello, World!" > output.txt

Standard Error (stderr)

File Descriptor: 2
Default Destination: Terminal screen
Purpose: Displays error messages

Examples

# Generate stderr output
ls /nonexistent-directory

# Redirect stderr to file
ls /nonexistent-directory 2> error.log



Advanced Stream Operations

Combining stdout and stderr

# Both to same file
ls /nonexistent-directory /etc > all_output.log 2>&1

# Separate files
./myscript.sh > output.log 2> error.log

# Using tee
ls /etc | tee output.log

Shell Redirection Operators

Operation Description
> file Redirects stdout to a file (overwrites if exists)
2> file Redirects stderr to a file
>> file Appends stdout to a file
2>> file Appends stderr to a file
< file Uses a file as stdin input
2>&1 Redirects stderr to stdout
> file 2>&1 Redirects both stdout and stderr to a file



Key Points

📊 Stream Types
  • Standard Streams
    - stdin (0): Input stream
    - stdout (1): Output stream
    - stderr (2): Error stream
  • Default Behavior
    - stdin: Reads from keyboard
    - stdout: Writes to screen
    - stderr: Writes to screen
  • Benefits
    - Flexible input/output control
    - Error handling separation
    - Script automation support



Reference