Standard Input, Standard Output, and Standard Error
Every command you run in Bash talks to the outside world through three channels: one that brings data in, one that carries normal results out, and one that carries error messages out. These channels are called standard input, standard output and standard error, and almost every feature in the rest of this section, from redirection to pipes, is built on them. Understanding them first makes the later operators (>, <, 2>, |) easy to read instead of something to memorize.
Understanding the Three Streams
When a program starts, the operating system gives it three ready-made connections. A program does not have to open them or know where they lead. It simply reads from one and writes to the other two.
| Name | Short name | Number | Purpose | Connected to by default |
|---|---|---|---|---|
| Standard input | stdin | 0 | Data the program reads | The keyboard |
| Standard output | stdout | 1 | Normal results | The terminal screen |
| Standard error | stderr | 2 | Error and diagnostic messages | The terminal screen |
The numbers in the table are called file descriptors. A file descriptor is a small integer that a process uses to refer to an open file or channel. The kernel always numbers the three standard streams 0, 1 and 2, and every redirection operator you will meet later uses those numbers.
The key idea is that the program writes to "standard output" without knowing whether that means a screen, a file or another program. Bash, acting as the shell, decides where each stream is connected before the program starts. That separation is what makes small commands easy to combine.
How the Streams Are Inherited
Bash itself is a program with the three standard streams connected to your terminal. When you type a command, Bash starts a new process for it, and the new process inherits the same three connections. Unless you ask for something different, the command's output appears on your screen and its input comes from your keyboard.
On Linux you can look at the connections of a process through the /proc file system. The /proc/self/fd folder lists the open file descriptors of the process that reads it:
ls -l /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2
In a terminal window, all three usually point to the same terminal device, for example /dev/pts/0. The exact device name differs from one session to the next. When the streams are connected elsewhere, the links show it. In one test run, standard input came from /dev/null and standard output and standard error were both attached to a pipe:
/proc/self/fd/0 -> /dev/null
/proc/self/fd/1 -> pipe:[428]
/proc/self/fd/2 -> pipe:[428]
The number inside pipe:[...] is an internal identifier and changes every time. The point is that a descriptor is only a connection, and a connection can lead to a terminal, a file, a pipe or a device.
Standard Output in Action
Most commands you have used so far write their results to standard output. Take a small file as an example:
printf 'apple\nbanana\ncherry\n' > fruits.txt
ls fruits.txt
Output:
fruits.txt
The name fruits.txt was written by ls to standard output, and the terminal displayed it. The command echo and the command printf behave the same way: whatever they print goes to standard output.
Standard Error in Action
Standard error is a second output channel that is meant for messages about problems. To see both channels at once, run ls on one file that exists and one that does not:
ls fruits.txt missing.txt
echo "status: $?"
Output:
ls: cannot access 'missing.txt': No such file or directory
fruits.txt
status: 2
Two different things happened here. The listing of the existing file went to standard output. The complaint about the missing file went to standard error. Both ended up on the screen because both streams are attached to the terminal, so you cannot tell them apart by looking. (The error line comes first because ls reports problems with its arguments before it prints the listing.)
The $? value is covered in a later lesson on exit codes. For now it is enough to know that status 2 means ls had a serious problem.
Seeing the Difference
The streams are separate, and you can prove it by sending only one of them somewhere else. This uses the > operator, which a following lesson explains fully. Here it sends standard output to a file:
ls fruits.txt missing.txt > out.txt
echo "out.txt holds:"
cat out.txt
Output:
ls: cannot access 'missing.txt': No such file or directory
out.txt holds:
fruits.txt
The listing went into out.txt, but the error message still appeared on the screen. It was not part of standard output, so the redirection did not capture it. The reverse also works. The operator 2> sends standard error to a file:
ls fruits.txt missing.txt 2> err.txt
echo "err.txt holds:"
cat err.txt
Output:
fruits.txt
err.txt holds:
ls: cannot access 'missing.txt': No such file or directory
Why Two Output Streams Exist
If errors and results shared one channel, you could not save the results of a command without also saving its error messages, and you could not hide the noise without hiding the answer. Separate channels let you choose.
A small script shows the idea. It prints a progress message, a warning and a final message:
#!/usr/bin/env bash
echo "Starting backup"
echo "Warning: disk almost full" >&2
echo "Backup finished"
The part >&2 makes the second echo write to standard error instead of standard output. Save the script as demo.sh, make it executable with chmod +x demo.sh, and run it normally:
./demo.sh
Output:
Starting backup
Warning: disk almost full
Backup finished
All three lines appear, so nothing looks different. Now save only the normal output to a log file:
./demo.sh > run.log
echo "run.log:"
cat run.log
Output:
Warning: disk almost full
run.log:
Starting backup
Backup finished
The warning stayed on the screen, where a person will notice it, while the normal messages went into the log. This is the reason that well-written scripts send warnings and errors to standard error.
Writing to Each Stream from a Script
Inside a script, echo writes to standard output unless you redirect it. To write to standard error, append >&2:
echo "normal message"
echo "error message" >&2
The operator >&2 means "send this command's standard output to wherever file descriptor 2 points". The form 1>&2, which spells out the source descriptor, means the same thing. On Linux you can also write to the special files that represent the streams:
echo "via dev stdout" > /dev/stdout
echo "via dev stderr" > /dev/stderr
These two names work on Linux and on macOS. The form >&2 is shorter and is what you will see in most scripts, so it is the one to learn first.
Standard Input in Action
Standard input is the channel a command reads from. Many commands read from it when you do not give them a file name. The command cat is the simplest example: with no arguments, it copies standard input to standard output.
In a terminal, running plain cat makes the command wait for you to type. Each line you finish with Enter is echoed back, and you end the input by pressing Ctrl + D, which signals end of input to the terminal:
$ cat
hello
hello
second line
second line
(press Ctrl + D)
$
Every line appears twice: once as you typed it and once as cat printed it. This session is illustrative and depends on your terminal, because it needs a keyboard to type on.
Standard input can also come from another command, through a pipe, which connects the standard output of one command to the standard input of the next:
printf 'one\ntwo\n' | cat
Output:
one
two
In this example cat was given no file name, yet it printed the text. It read one and two from standard input, and the pipe supplied them. The | operator has its own lesson later in this section.
The same behavior appears with other commands. grep and sort read from standard input when no file is given:
printf 'red\ngreen\nblue\n' | grep r
printf 'b\na\n' | sort
Output:
red
green
a
b
The first command printed only the lines that contain the letter r. The word blue has no r, so grep dropped it. The second command sorted its two lines alphabetically.
Reading Input Inside a Script
The built-in command read takes one line from standard input and stores it in a variable. Here the line comes from a pipe:
echo "Ana" | { read -r name; echo "Hello, $name"; }
Output:
Hello, Ana
In a normal script, standard input is your keyboard, so read waits for you to type a line. The earlier lesson on reading user input covers the options of read. The important point here is that read, like cat and grep, simply reads from file descriptor 0 and does not care where the data comes from.
Commands That Take a File or Standard Input
Many commands accept either a file name or standard input. The results are the same, but there is one visible difference. When you give wc a file name, it prints the name. When the data comes from standard input, it has no name to print:
wc -l fruits.txt
wc -l < fruits.txt
cat fruits.txt | wc -l
Output:
3 fruits.txt
3
3
The second command uses the < operator, which connects a file to standard input. The third uses a pipe. The next lessons explain both in detail.
Detecting Whether a Stream Is a Terminal
A script can ask whether a stream is connected to a terminal by using the test -t followed by a file descriptor number. This is useful for deciding whether to print colors or to ask a question:
[ -t 0 ] && echo "stdin is a terminal" || echo "stdin is not a terminal"
[ -t 1 ] && echo "stdout is a terminal" || echo "stdout is not a terminal"
[ -t 2 ] && echo "stderr is a terminal" || echo "stderr is not a terminal"
In a test run where input came from /dev/null and output went to a pipe, each line reported that the stream was not a terminal:
stdin is not a terminal
stdout is not a terminal
stderr is not a terminal
Typed directly into a terminal window, the same three lines would report that each stream is a terminal. The test reports the real connection at that moment, which can change when a script is started from a scheduler, from another script or with its output sent to a file.
Pipes Carry Only Standard Output
A pipe connects standard output to standard input. It does not carry standard error. This matters when a command in a pipeline fails:
ls fruits.txt missing.txt | wc -l
Output:
ls: cannot access 'missing.txt': No such file or directory
1
The wc -l command counted one line, the name fruits.txt. The error message was not sent through the pipe. It went straight to the terminal, because standard error was still attached to the screen. The lesson on combining standard output and standard error shows how to send both through a pipe when you want to.
Exit Status Is a Separate Signal
A command reports success or failure through its exit status, not through standard error. The two are related, because programs usually print a message and return a non-zero status together, but they are independent. Hiding the message does not change the status:
ls fruits.txt missing.txt 2> /dev/null
echo "status: $?"
Output:
fruits.txt
status: 2
The special file /dev/null discards everything written to it. The error message disappeared, but the status is still 2, so a script that checks $? still knows something went wrong.
The Redirection Operators Ahead
The next lessons look at each way of changing where the three streams go. This table previews the operators and the lesson that explains each one:
| Operator | Meaning |
|---|---|
> file | Send standard output to a file, replacing its contents |
>> file | Append standard output to a file |
< file | Read standard input from a file |
2> file | Send standard error to a file |
2>&1 | Send standard error to the same place as standard output |
| | Connect the standard output of one command to the standard input of another |
All of them work by changing what file descriptors 0, 1 and 2 point to for a single command, which is why the numbers introduced in this lesson appear in them.