How to Redirect Bash Output to a File
-
Use the
>
and>>
Operators to Redirect Output to a File in Bash -
Use the
tee
Command to Redirect Output to a File in Bash
This small article is about the methods in Bash scripting for redirecting the output of the commands to a file instead of the standard console.
There are several ways to achieve this redirection. Here we will discuss some of them.
Use the >
and >>
Operators to Redirect Output to a File in Bash
The two redirection operators >
and >>
redirect the output of any command to a specified file instead of stdout
or console.
- Using the
>
operator, the output is inserted in a file replacing all the previous file’s contents. - Using the
>>
operator, the output is appended to the end of the file, keeping the previous content as it is.
Remember that you do not need to create the file explicitly before using this command; you need to specify the correct path, and Bash will create a new file if the file does not exist.
The syntax for this command is:
[command] > /path/to/your/file
Let’s look at the example below.
You can see from the picture above that after executing the first command, no output was shown on the screen, but all of the output is placed in the file and viewed in the next command.
We will look at the working of the >>
operator.
You can see in the image that the output of the uname
command is appended at the end of the file.
Use the tee
Command to Redirect Output to a File in Bash
The tee
command is also used for redirecting the output to a file. The difference is that it not only sends the output to the file but also shows it on the screen.
Remember that you do not need to create the file explicitly before using this command; you need to specify the correct path, and Bash will create a new file if the file does not exist.
The syntax for this command is:
[command] | tee /path/to/your/file
Let’s look at the example below.
This command replaces all the file contents with this new content. If you want to keep the previous content and append the file, we can use this command with an -a
option like below.
Thus, we can see there are a lot of ways to redirect the output to a file.
We have discussed some of them here. There are several others as well.