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:
| fd | Name | Default | Used for |
|---|---|---|---|
| 0 | stdin | keyboard | input |
| 1 | stdout | terminal | normal output |
| 2 | stderr | terminal | errors 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
| Syntax | Effect |
|---|---|
cmd > file | stdout to file, overwriting it |
cmd >> file | stdout to file, appending |
cmd 2> file | stderr to file |
cmd 2>> file | stderr appended |
cmd > file 2>&1 | both stdout and stderr to file |
cmd &> file | same, Bash shorthand |
cmd > /dev/null | throw stdout away |
cmd 2> /dev/null | throw errors away |
echo "first line" > notes.logecho "second line" >> notes.logcat notes.logfirst linesecond lineNow 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.txtls: 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 directoryWith > 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 fileThe 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.txterror: config not foundresult-dataThe 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/hosts44 /etc/hostsWith <, 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 3Pipes 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 -l2tee: 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.txt22026-11-28T09:06:02Z ERROR database connection timeout host=db12026-11-28T09:15:10Z ERROR payment service returned 503tee -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 pipefailcat: /nope: No such file or directoryexit code: 0cat: /nope: No such file or directoryexit code: 1With 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- The marker (
EOFhere, 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. <<-EOFstrips leading tabs (not spaces), so you can indent the block inside anifor 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_HOSTEOFAnd writing a script or a file that must keep its $ signs literally:
cat > /usr/local/bin/hello <<'EOF'#!/usr/bin/env bashecho "Hello, $USER"EOFHere-documents also feed commands that read stdin, such as kubectl apply -f -:
kubectl apply -f - <<EOFapiVersion: v1kind: ConfigMapmetadata: name: app-configdata: ENV: "$env"EOFHere-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"1alpha / beta gammaCommand 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.txt7 report.txt( … ) 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- 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 intogzip.pipefailmakes the recorded exit code reflect apg_dumpfailure, not justgzip.-schecks whether the error file has content, so monitoring can alert on it.
Common mistakes
> filewhen 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 emptiesfilebeforesortreads it, so you get an empty file. Write to a temporary file and move it, or usesort -o file file.- Spaces around the here-document end marker:
EOFdoes 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
- Run
ls /etc /nopeso that the listing goes tolist.txtand the error goes tolist.err. Check both files. - Count the WARN and ERROR lines in the app log using one pipeline, and save them with
teeat the same time. - Show that
false | trueexits 0, then turn onpipefailand show it exits 1. - Use a here-document to create
app.envcontainingPORT=8080andENV=$USERwith the variable expanded. Then createliteral.txtwhere$USERstays as text. - Use a here-string to count the words in
"one two three"withwc -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 outputKey takeaways
- stdout (1) carries data, stderr (2) carries messages; keep them separate in your scripts with
>&2. >overwrites,>>appends, and> file 2>&1captures everything in the right order.- Pipes pass stdout to the next command;
teesaves a copy along the way. set -o pipefailstops failures from hiding in the middle of a pipeline.- Here-documents generate multi-line files and input; quote the marker to keep
$literal.