iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Pipes & Redirection

Pipes (|) glue commands together: the stdout of one becomes the stdin of the next. Combined with redirection (>, >>, 2>&1) and xargs they are the unix superpower.

Pipes + redirection in practice

EXAMPLE
# Pipe one command into another
ls -1 | wc -l                          # count files

# Chain three: tail -> grep -> awk -> head
tail -f /var/log/app.log \
    | grep ERROR \
    | awk '{print $1, $2, $NF}' \
    | head -20

# Redirect stdout, stderr, and both
command > out.txt              # stdout only
command 2> err.txt             # stderr only
command > out.txt 2> err.txt   # split
command > out.txt 2>&1         # merge — old style
command &> out.txt             # merge — bash shortcut
command 2>/dev/null            # silence stderr

# Process substitution — feed a command as if it were a file
diff <(sort file1) <(sort file2)

# tee — split a pipe (also write to a file)
make 2>&1 | tee build.log | grep -E 'warning|error'

# xargs — turn input lines into command arguments
find . -name '*.tmp' | xargs rm
find . -name '*.log' -print0 | xargs -0 -P 4 gzip   # 4 parallel workers, null-delimited

Why it matters

Always use -print0 + xargs -0 when filenames might contain spaces or newlines. It’s the unix equivalent of parameterised SQL.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
ps aux | grep node | grep -v grep
command &> output.log         # stdout + stderr
Try it Yourself »

Exercise

Pipe character.

ps aux grep node

Test yourself

Q1. Send stdout to stdin of next command with…
Q2. Append to a file with…
Q3. Redirect both stdout + stderr to a file with…

Discussion

Loading…