Skip to content
$ lynuxpro
← Bash Scripting

LESSON 9 OF 17 · INTERMEDIATE · 18 MIN

Pipes, redirection and here-documents

HOW IT WORKSWhere a command's input and output go

PROCESSstdin (fd 0)keyboard / < filecommandreads 0, writes 1 and 2stdout (fd 1)normal outputstderr (fd 2)errors> out.txtor | next cmd2> err.logor 2>&1
1/5

Every process starts with three streams: stdin (0), stdout (1) and stderr (2).

Every program in Linux reads input and writes output through streams. Bash lets you connect those streams to files, to other programs or to text written right inside your script. Understanding streams explains why an error message still appears on screen when you redirect output, how to keep logs clean, and how scripts generate config files on the fly.

In simple words

  • Standard streams: every program has input (stdin), normal output (stdout) and error output (stderr).
  • Redirection: sending output to a file (>), adding to a file (>>), or reading input from a file (<).
  • 2>&1: sends error output to the same place as normal output.
  • Pipe: | sends one command's output into the next command.
  • Here-document: multi-line text written right inside the script and fed to a command.

The three standard streams

Every process starts with three open streams, each with a number called a file descriptor:

fdNameDefaultUsed for
0stdinkeyboardinput
1stdoutterminalnormal output
2stderrterminalerrors and diagnostics

stdout and stderr both appear on your screen by default, which hides the fact that they are separate. Redirection makes the difference visible.

Redirecting output

SyntaxEffect
cmd > filestdout to file, overwriting it
cmd >> filestdout to file, appending
cmd 2> filestderr to file
cmd 2>> filestderr appended
cmd > file 2>&1both stdout and stderr to file
cmd &> filesame, Bash shorthand
cmd > /dev/nullthrow stdout away
cmd 2> /dev/nullthrow errors away
echo "first line" > notes.logecho "second line" >> notes.logcat notes.log
SHELLbashutf-8 · 3L
first linesecond line
OUTPUTterminalutf-8 · 2L

Now separate output from errors. ls lists one file that exists and one that does not:

ls /etc/hosts /nopels /etc/hosts /nope > out.txtcat out.txtls /etc/hosts /nope 2> err.txtcat err.txt
SHELLbashutf-8 · 5L
ls: cannot access '/nope': No such file or directory/etc/hostsls: cannot access '/nope': No such file or directory/etc/hosts/etc/hostsls: cannot access '/nope': No such file or directory
OUTPUTterminalutf-8 · 6L

With > out.txt, the error still appeared on screen: only stdout went into the file. With 2> err.txt, the normal output stayed on screen and only the error went into the file.

2>&1 and why order matters

2>&1 means "send fd 2 to wherever fd 1 is going right now". Bash processes redirections left to right, so:

cmd > all.log 2>&1    # stdout to file, then stderr to the same place: both in the filecmd 2>&1 > all.log    # stderr to the terminal (where stdout was), then stdout to the file
SHELLbashutf-8 · 2L

The first form is what you want almost every time. For cron jobs and background tasks, >> /var/log/job.log 2>&1 captures everything.

Writing your own errors to stderr

Your scripts should follow the same convention: data on stdout, messages and errors on stderr. Use >&2:

printf '#!/usr/bin/env bash\necho "error: config not found" >&2\necho "result-data"\n' > report.shchmod +x report.sh./report.sh > result.txtcat result.txt
SHELLbashutf-8 · 4L
error: config not foundresult-data
OUTPUTterminalutf-8 · 2L

The user still sees the error, and result.txt contains only clean data that another program can read. This is why log() { … >&2; } in the functions lesson printed to stderr.

Redirecting input

< feeds a file into a command's stdin:

wc -l < /etc/hostswc -l /etc/hosts
SHELLbashutf-8 · 2L
44 /etc/hosts
OUTPUTterminalutf-8 · 2L

With <, wc does not know the file name, so it prints only the number, which is handy in scripts: lines=$(wc -l < file).

Pipes

A pipe | connects the stdout of one command to the stdin of the next. Each program does one job and passes its result along:

cat /var/log/app/app.log | grep -v INFO | wc -lps aux | grep nginx | head -n 3
SHELLbashutf-8 · 2L

Pipes carry stdout only. Errors still go to the screen. To send both through a pipe, use 2>&1 | (or |& in Bash):

ls /etc/hosts /nope 2>&1 | wc -l
SHELLbashutf-8 · 1L
2
OUTPUTterminalutf-8 · 1L

tee: save and show at the same time

tee copies its input to a file and to stdout, so you can log output and keep watching it:

grep ERROR /var/log/app/app.log | tee errors.txt | wc -lcat errors.txt
SHELLbashutf-8 · 2L
22026-11-28T09:06:02Z ERROR database connection timeout host=db12026-11-28T09:15:10Z ERROR payment service returned 503
OUTPUTterminalutf-8 · 3L

tee -a appends instead of overwriting. A classic trick: sudo does not apply to redirections, so sudo echo x > /etc/file fails; echo x | sudo tee /etc/file works.

Pipelines and exit codes

A pipeline's exit code is the exit code of its last command. A failure earlier in the pipe is hidden:

cat /nope | sortecho "exit code: $?"set -o pipefailcat /nope | sortecho "exit code: $?"set +o pipefail
SHELLbashutf-8 · 6L
cat: /nope: No such file or directoryexit code: 0cat: /nope: No such file or directoryexit code: 1
OUTPUTterminalutf-8 · 4L

With pipefail, a pipeline fails if any command in it fails. Safe scripts turn it on at the top (you will see the full "strict mode" next lesson).

Here-documents: multi-line input written in the script

A here-document sends several lines of text to a command's stdin. Everything up to the closing marker is input:

cat <<EOFDeploy summary  app:     $app  version: $version  time:    $(date +%F)EOF
SHELLbashutf-8 · 6L
  • The marker (EOF here, but any word works) must be alone on its closing line, with no spaces before or after.
  • Variables and $( ) are expanded inside, like in double quotes.
  • Quote the marker, <<'EOF', to turn expansion off. Use this when the text itself contains $, such as a script or a template.
  • <<-EOF strips leading tabs (not spaces), so you can indent the block inside an if or a function.

The most common use is generating a config file:

cat > /etc/myapp/app.conf <<EOFport=${PORT:-8080}log_level=${LOG_LEVEL:-info}db_host=$DB_HOSTEOF
SHELLbashutf-8 · 5L

And writing a script or a file that must keep its $ signs literally:

cat > /usr/local/bin/hello <<'EOF'#!/usr/bin/env bashecho "Hello, $USER"EOF
SHELLbashutf-8 · 4L

Here-documents also feed commands that read stdin, such as kubectl apply -f -:

kubectl apply -f - <<EOFapiVersion: v1kind: ConfigMapmetadata:  name: app-configdata:  ENV: "$env"EOF
SHELLbashutf-8 · 8L

Here-strings

A here-string, <<<, feeds a single string to stdin. It is shorter than echo … | and does not create a subshell:

grep -c web <<< "web1 web2 db1"read -r first rest <<< "alpha beta gamma"echo "$first / $rest"
SHELLbashutf-8 · 3L
1alpha / beta gamma
OUTPUTterminalutf-8 · 2L

Command grouping

To redirect the output of several commands at once, group them with { …; }:

{ echo "== hosts"; cat /etc/hosts; echo "== date"; date +%F; } > report.txtwc -l report.txt
SHELLbashutf-8 · 2L
7 report.txt
OUTPUTterminalutf-8 · 1L

( … ) does the same but runs the commands in a subshell, so a cd or variable inside does not affect the rest of the script.

Real-world scenario: a nightly job with clean logging

A cron job runs a database export. Operators want everything in a log file, a timestamp on every run, errors kept separate for alerting, and the export itself untouched by any log text:

#!/usr/bin/env bashset -o pipefaillog=/var/log/export.logerr=/var/log/export.err {  echo "=== $(date '+%F %T') export starting"  pg_dump shop 2>> "$err" | gzip > "/backups/shop-$(date +%F).sql.gz"  echo "=== exit code $?"} >> "$log" if [[ -s $err ]]; then  echo "export produced errors, see $err" >&2  exit 1fi
SHELLbashutf-8 · 15L
  • The { } group appends all progress messages to one log.
  • pg_dump's errors go to their own file, while its data flows through the pipe into gzip.
  • pipefail makes the recorded exit code reflect a pg_dump failure, not just gzip.
  • -s checks whether the error file has content, so monitoring can alert on it.

Common mistakes

  • > file when you meant >>: the file is emptied first. One wrong character can wipe a log.
  • cmd 2>&1 > file: errors still go to the screen. Write > file 2>&1.
  • sort file > file: the shell empties file before sort reads it, so you get an empty file. Write to a temporary file and move it, or use sort -o file file.
  • Spaces around the here-document end marker: EOF does not end the block (except tabs with <<-).
  • Unquoted marker when the content has $: variables you meant literally get expanded (usually to nothing).
  • Hidden pipeline failures without pipefail.

Practice

  1. Run ls /etc /nope so that the listing goes to list.txt and the error goes to list.err. Check both files.
  2. Count the WARN and ERROR lines in the app log using one pipeline, and save them with tee at the same time.
  3. Show that false | true exits 0, then turn on pipefail and show it exits 1.
  4. Use a here-document to create app.env containing PORT=8080 and ENV=$USER with the variable expanded. Then create literal.txt where $USER stays as text.
  5. Use a here-string to count the words in "one two three" with wc -w.

Cheat sheet

> file      >> file         stdout overwrite / append2> file     2>> file        stderr> file 2>&1   &> file       both> /dev/null 2>&1            silence everythingecho "msg" >&2              write to stderrcmd < file                  file as stdina | b       a 2>&1 | b      pipe stdout / bothcmd | tee [-a] file         save and showset -o pipefail             fail if any pipe stage failscat <<EOF … EOF             here-document (expands)cat <<'EOF' … EOF           here-document (literal)cmd <<< "$string"           here-string{ a; b; } > file            group output
OUTPUTterminalutf-8 · 13L

Key takeaways

  • stdout (1) carries data, stderr (2) carries messages; keep them separate in your scripts with >&2.
  • > overwrites, >> appends, and > file 2>&1 captures everything in the right order.
  • Pipes pass stdout to the next command; tee saves a copy along the way.
  • set -o pipefail stops failures from hiding in the middle of a pipeline.
  • Here-documents generate multi-line files and input; quote the marker to keep $ literal.