Back to Blog

Pipes & Redirection in Zsh — Complete Guide for Beginners #16

Sandy LaneSandy Lane

Video: Pipes & Redirection in Zsh — Complete Guide for Beginners #16 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Pipes & Redirection in Zsh — Complete Guide for Beginners

Mastering pipes and redirection in Zsh allows you to efficiently control the flow of data between commands and files. This guide covers standard input/output streams, chaining commands with pipes, redirecting output and errors, and advanced techniques like here documents and the tee command for simultaneous output.

Code

# Standard streams:
# stdin (0), stdout (1), stderr (2)

# Pipe operator: send stdout of one command to stdin of another
ls -l | grep ".txt"

# Chain multiple pipes
cat file.txt | grep "error" | sort | uniq

# Redirect stdout to a file (overwrite)
echo "Hello World" > output.txt

# Append stdout to a file
echo "Another line" >> output.txt

# Discard stdout by redirecting to /dev/null
command > /dev/null

# Prevent overwriting files with noclobber option
setopt noclobber
echo "New content" > output.txt  # Fails if output.txt exists
# Use '>|' to override noclobber
echo "Force overwrite" >| output.txt

# Redirect stderr to a file
ls non_existing_file 2> error.log

# Merge stderr into stdout
command >&1

# Redirect both stdout and stderr to the same file
command > all_output.log 2>&1

# Separate stdout and stderr to different files
command > stdout.log 2> stderr.log

# Here document: feed multiline input to a command
cat << EOF
Line 1
Line 2
EOF

# Here string: feed a single string as input
grep "pattern" <<< "search this string"

# Use tee to output to file and stdout simultaneously
ls -l | tee output.txt

# Append with tee
echo "New line" | tee -a output.txt

Key Points

  • Pipes (|) connect the stdout of one command to the stdin of another, enabling powerful command chains.
  • Use > and >> to redirect output to files, overwriting or appending respectively.
  • Redirect stderr separately with 2> or merge it with stdout using >&1 for combined output.
  • Here documents (<<) and here strings (<<<) provide convenient ways to supply input directly within scripts.
  • The tee command allows you to write output to a file while still displaying it on the terminal, with -a to append.