shBash
BeginnerLesson 2 of 15

Pipes & Redirection – Bash

Chain programs and direct input/output into files.

Every program has three data channels: stdin (0, input), stdout (1, normal output) and stderr (2, error messages). With > you write stdout to a file (overwrites), >> appends, < reads stdin from a file, 2> redirects stderr.

echo "first line" > log.txt      # create/overwrite the file
echo "second line" >> log.txt     # append
wc -l < log.txt                    # 2   (input from a file)
ls /gibt-es-nicht 2> fehler.txt    # redirect errors only
ls /gibt-es-nicht > /dev/null 2>&1 # make everything disappear
cmd > alles.log 2>&1               # stdout AND stderr into the same file

The pipe | connects the stdout of the left program to the stdin of the right one. This lets you build powerful workflows from simple tools – the Unix philosophy: "Each program does one thing well."

printf 'b\na\nb\nc\nb\n' | sort | uniq -c | sort -rn
#       3 b
#       1 c
#       1 a          (frequencies, descending; ties: order not guaranteed)

ls | wc -l                                     # number of entries
cat server.log | grep ERROR | wc -l            # count error lines (shorter: grep -c ERROR server.log)
ls -l | tee liste.txt | head -n 3              # tee: into a file AND on to the pipe
Warningsort < datei > datei empties the file: the shell opens (and truncates) the output file before the program reads. Use sort datei -o datei or a temporary file. Also: 2>&1 must come after > datei – 2>&1 > datei sends stderr to the terminal.
TipBash only (not POSIX sh): cmd &> datei is shorthand for > datei 2>&1. In scripts that should run on sh, write the long form.