There are times when you want to redirect the output of specific output to a file so you can examine the error later.
And in that case, you can redirect the data stream to the file.
So in this tutorial, I will walk you through how to redirect the output to a file.
How to redirect output to file
Contents
Before I jump to the how-to part, it is necessary to know the basics of data streams.
There are 3 three types of data streams:
- Input data stream (denoted as 0)
- Output data stream (denoted as 1)
- Error data stream (denoted as 2)
📋
You can not use 0
to redirect the input data stream. For that, you have to use <
or you can pipe command.
Now, let’s have a look at redirection symbols and numbers for redirection:
Indicator | Description |
---|---|
0 |
Input data stream. |
1 |
Output data stream. |
2 |
Error data stream. |
> |
Redirects std output to a file or command. |
< |
Redirects std input from a file or command. |
>> |
Appends the std output to a file. |
2> |
Redirects std error to a file or command. |
2>> |
Appends std error to a file. |
Let’s have a look at examples.
1. Redirecing output to a file (overrides existing data)
As I mentioned above, you have to use the >
symbol in the following manner:
command > Filename
For example, here, I used the sudo apt update
command and redirected the output to the update.txt
file:
sudo apt update > update.txt
And now, if I use the cat command to print the content of the file, it should bring the output of the apt update
command:
cat update.txt
But wait, if you use to redirect the output in the shown way, it will override the existing content of the file.
And here’s how you do it.
2. Redirect output to a file without overriding
As I mentioned earlier, if you don’t want to override the existing file content, then you use the >>
instead of >
:
command >> Filename
For example, here, I will be using a sample text file named Hello.txt
which contains the following:
And now, I will use the print command and redirect the output to the Hello.txt
file:
echo Lines to be appended >> Hello.txt
There you have it!
Bonus: Redirect output using the tee command
🚧
Unlike redirection, using the tee command you can only override the existing file content to redirect its data.
If you don’t like the idea of using the redirection indicators, you can use the tee command in the following manner to have the same effect:
command | tee Filename
Here I used the file named Hello.txt
which already had some text inside:
echo Hello again | tee Hello.txt
More on redirection of data
If you want to learn more about how you redirect the data streams with multiple possibilities, here’s a detailed guide for you:
I hope you will find this guide helpful.