Standard Input, Standard Output, and Standard Error

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 56 of 205

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.

NameShort nameNumberPurposeConnected to by default
Standard inputstdin0Data the program readsThe keyboard
Standard outputstdout1Normal resultsThe terminal screen
Standard errorstderr2Error and diagnostic messagesThe 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:

OperatorMeaning
> fileSend standard output to a file, replacing its contents
>> fileAppend standard output to a file
< fileRead standard input from a file
2> fileSend standard error to a file
2>&1Send 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Standard Input, Standard Output, and Standard Error and get answers drawn from it.

Signed-in readers only.