Redirecting Input and Output in Linux

CompTIABeginner
Practice Now

Introduction

In this lab, you will learn the fundamental techniques for redirecting input and output in the Linux shell. You will explore how to control the flow of data from commands by manipulating the three standard streams: standard output (stdout), standard error (stderr), and standard input (stdin). This lab provides hands-on practice with essential redirection operators, enabling you to save command output, manage error messages, and provide input to commands from files.

Throughout the exercises, you will use the > operator to send command output to a file, overwriting existing content, and the >> operator to append output without losing data. You will also learn to specifically redirect error messages using 2> and how to combine both standard output and standard error into a single file. Finally, you will use the tee command to simultaneously display output on the screen and save it to a file, and practice redirecting standard input using the < operator to make a command read from a file instead of the keyboard.

Redirect Standard Output with the > Operator

In this step, you will learn how to redirect the standard output of a command. In a Linux shell, most commands produce some output. By default, this output, known as "Standard Output" (or stdout), is displayed on your terminal screen. However, you can redirect this output to a file using the > operator. This is useful for saving command results, creating log files, or generating reports.

First, let's execute a simple command and see its output on the terminal.

echo "Hello from LabEx"

You should see the following output directly in your terminal:

Hello from LabEx

Now, let's redirect this output to a file instead. We'll use the > operator followed by a filename. This tells the shell to send the output of the echo command to a file named hello.txt in your current directory (~/project).

Execute the following command:

echo "Hello from LabEx" > hello.txt

Notice that this time, you don't see any output on the terminal. That's because the output was sent to the hello.txt file. You can verify the contents of the file using the cat command:

cat hello.txt

The output will show the text that was redirected:

Hello from LabEx

The > operator will create the file if it doesn't exist. Be careful, if the file already exists, the > operator will overwrite its entire content without any warning. Let's see this in action.

First, let's list the contents of the current directory and save it to a new file called file_list.txt.

ls -l > file_list.txt

Now, view the contents of file_list.txt:

cat file_list.txt

You will see a listing of the files in your project directory, which should look something like this:

total 4
-rw-rw-r-- 1 labex labex  0 Jun 25 14:56 file_list.txt
-rw-rw-r-- 1 labex labex 17 Jun 25 14:56 hello.txt

Now, let's run a different command and redirect its output to the same file, file_list.txt.

echo "This is new content." > file_list.txt

If you check the contents of file_list.txt again, you will see that the original file list has been replaced.

cat file_list.txt

The output is now:

This is new content.

This demonstrates the overwriting behavior of the > operator. In the next step, you will learn how to append output to a file without overwriting it.

Append Standard Output with the >> Operator

In this step, you will learn how to add output to the end of a file without deleting its existing content. In the previous step, you saw that the > operator overwrites the destination file. To avoid this, you can use the append operator, >>. This operator is extremely useful for tasks like maintaining a running log file where you want to add new entries over time.

Let's start by creating a file with some initial content. We'll name it greetings.txt.

echo "Hello, this is the first line." > greetings.txt

Now, verify its content:

cat greetings.txt

The output should be:

Hello, this is the first line.

Next, instead of overwriting the file, let's append a new line to it using the >> operator.

echo "This is the second line, appended." >> greetings.txt

Check the content of greetings.txt again.

cat greetings.txt

This time, you will see that the new line has been added after the original content:

Hello, this is the first line.
This is the second line, appended.

The >> operator is perfect for creating log files. Let's create a simple log file named activity.log and add a timestamp to it using the date command.

date > activity.log

Now, let's append another timestamp to the same file.

date >> activity.log

View the final activity.log file to see both entries.

cat activity.log

The output will show two timestamps, demonstrating that the second command appended its output instead of overwriting the file. The exact times will vary.

Wed Jun 25 14:56:53 CST 2025
Wed Jun 25 14:56:56 CST 2025

This shows how >> preserves existing data and adds new data to the end of a file, making it a safe way to update files with new information.

Redirect Standard Error with the 2> Operator

In this step, you'll learn how to manage error messages. Besides standard output (stdout), commands also produce another type of output called "Standard Error" (stderr). This is a separate stream used specifically for error messages and diagnostics. By default, both stdout and stderr are displayed on your terminal, but the redirection operators you've learned so far (> and >>) only affect stdout.

To redirect stderr, you need to specify its file descriptor, which is 2. The > operator is actually a shorthand for 1>, where 1 is the file descriptor for stdout. So, to redirect stderr, you use 2>.

Let's generate an error to see this in action. We'll try to list a file that doesn't exist.

ls non_existent_file

This command will fail and print an error message to your terminal:

ls: cannot access 'non_existent_file': No such file or directory

Now, let's try to redirect this using the standard > operator.

ls non_existent_file > output.txt

Notice that the error message is still printed to the terminal. The > operator did not capture it. If you check the output.txt file, you'll find that it's empty.

cat output.txt

The command produces no output because no standard output was generated, only standard error.

Now, let's correctly redirect the standard error to a file named error.log using 2>.

ls non_existent_file 2> error.log

This time, no message appears on the terminal. The error has been successfully redirected. You can view the contents of error.log to see the captured message.

cat error.log

The output will be the error message from the ls command:

ls: cannot access 'non_existent_file': No such file or directory

Just like >> appends standard output, you can use 2>> to append standard error to a file. Let's try to list another non-existent file and append the error to our error.log.

ls another_fake_file 2>> error.log

Now, check the contents of error.log again.

cat error.log

You will see that the new error message has been added to the end of the file.

ls: cannot access 'non_existent_file': No such file or directory
ls: cannot access 'another_fake_file': No such file or directory

This technique is very useful for separating normal output from error messages, allowing you to log errors for later review without cluttering your main output files.

Redirect Both stdout and stderr to a Single File

In this step, you will learn how to capture all output from a command—both standard output and standard error—into a single file. This is particularly useful when you want a complete record of a script or command's execution, including any errors that occurred.

Let's use a command that produces both stdout and stderr. We will try to list a file that exists (/etc/passwd) and one that does not (non_existent_file).

ls -l /etc/passwd non_existent_file

You will see two types of output on your terminal. The first line is the standard error, and the second is the standard output.

ls: cannot access 'non_existent_file': No such file or directory
-rw-r--r-- 1 root root 1916 Jul 18  2024 /etc/passwd

If you try to redirect this using only > for stdout, the error message will still appear on the screen.

ls -l /etc/passwd non_existent_file > output_only.txt

Output on terminal:

ls: cannot access 'non_existent_file': No such file or directory

And output_only.txt will only contain the standard output:

cat output_only.txt
-rw-r--r-- 1 root root 1916 Jul 18  2024 /etc/passwd

To redirect both streams to one file, you can use the &> operator. This is a convenient shorthand that sends both stdout (file descriptor 1) and stderr (file descriptor 2) to the specified file.

Let's try it. We'll redirect all output to a file named combined.log.

ls -l /etc/passwd non_existent_file &> combined.log

This time, nothing is printed to the terminal. All the output has been captured in combined.log. Let's view its contents:

cat combined.log

You will see that the file contains both the standard output and the standard error:

ls: cannot access 'non_existent_file': No such file or directory
-rw-r--r-- 1 root root 1916 Jul 18  2024 /etc/passwd

There is also a more traditional, but slightly more complex, syntax to achieve the same result: > file 2>&1. Let's break it down:

  • > file: This redirects standard output (file descriptor 1) to file.
  • 2>&1: This redirects standard error (file descriptor 2) to the same location as standard output (file descriptor 1). Since stdout is already going to file, stderr is sent there as well.

Let's try this method, saving the output to combined_traditional.log.

ls -l /etc/passwd non_existent_file > combined_traditional.log 2>&1

Again, no output appears on the terminal. Verifying the file's content shows the same result:

cat combined_traditional.log
ls: cannot access 'non_existent_file': No such file or directory
-rw-r--r-- 1 root root 1916 Jul 18  2024 /etc/passwd

While &> is shorter and often preferred, you will frequently see 2>&1 in older scripts, so it's important to understand what it does. To append both streams, you can use &>> or >> file 2>&1.

Use tee to Split Output and Redirect Standard Input with <

In this final step, you will explore two complementary redirection concepts: splitting output with the tee command and providing input to a command from a file using the < operator.

Splitting Output with tee

Sometimes, you want to save a command's output to a file while also viewing it on the terminal simultaneously. The > and >> operators redirect output exclusively to a file, hiding it from the screen. The tee command solves this by splitting the output, sending it to both a file and to standard output (your screen). It's named after a T-splitter in plumbing, which splits a flow into two paths.

Let's see it in action. We will list the contents of the /etc/ directory and use tee to both display the list on the screen and save it to a file named etc_listing.txt.

ls /etc/ | tee etc_listing.txt

You will see the full directory listing printed to your terminal. At the same time, the tee command has written the exact same output to etc_listing.txt. You can verify this:

cat etc_listing.txt

The contents of the file will match what you saw on the screen.

By default, tee overwrites the destination file. To append to a file instead, you use the -a option. This is very useful for logging. Let's create a log file and append two entries.

date | tee system_log.txt
echo "User labex performed a system check." | tee -a system_log.txt

The first command creates system_log.txt with the current date. The second command, using tee -a, appends a new line without deleting the date. Let's check the final file:

cat system_log.txt

The output will show both lines:

Wed Jun 25 14:56:53 CST 2025
User labex performed a system check.

Redirecting Standard Input with <

Now let's look at the opposite of output redirection: redirecting standard input (stdin). Many commands, like sort, wc, or cat, can read data from stdin (usually your keyboard). The < operator allows you to tell a command to get its input from a file instead.

First, let's create a simple file with a list of items. We'll name it items.txt.

echo "banana" > items.txt
echo "apple" >> items.txt
echo "cherry" >> items.txt

Now we have a file items.txt with three unsorted items. The sort command can sort lines of text. Let's use < to feed items.txt into the sort command.

sort < items.txt

The command will read the contents of items.txt as its input, sort them, and print the result to its standard output (the terminal):

apple
banana
cherry

This is functionally similar to running sort items.txt, but it demonstrates the powerful concept of redirecting a file to a command's standard input. This becomes essential when working with commands that can only read from stdin and don't accept a filename as an argument.

As a final example, consider cat < items.txt. This tells cat to read its input from items.txt and, since cat's job is to print its input to its output, it displays the file's contents on the screen.

cat < items.txt

This concludes our tour of basic I/O redirection in Linux. You now have the tools to control where your commands get their input from and where their output goes.

Summary

In this lab, you learned the fundamentals of redirecting command output in Linux. You started by using the > operator to send the standard output (stdout) of a command to a file, noting that this operator will overwrite the destination file if it already exists. To avoid overwriting, you used the >> operator to append output to the end of a file. You also practiced redirecting standard error (stderr) to a file using the 2> operator, which is useful for capturing error messages separately from standard output.

Furthermore, the lab demonstrated how to combine these concepts by redirecting both stdout and stderr to a single file for comprehensive logging. You explored the tee command as a method to split output, allowing it to be saved to a file while simultaneously being displayed on the terminal. Finally, you learned to redirect standard input (stdin) using the < operator, enabling a command to read its input from a file instead of from the keyboard.