How to save the command output in a file in a Linux terminal

Ankur Gupta
Ankur Guptahttps://antarjaal.in
Web developer by profession, Over 10 years experience of building websites and web applications. Currently working on Epaper CMS Cloud (Software As Service based product). Special interest in computer and technology. After writing on the blogger platform for years, started his own tech portal Antarjaal.In.

When you enter a command in Linux terminal, you immediately get the output. But sometimes it is required to save this result for any future use. How good it would be if we could save the result in a file.

So today we are going to discuss about how you can save the output of any Linux command in a file.

Method 1: Using Redirection Operator in Linux

When you use the redirection operator, the result of your command does not appear in the terminal and goes directly in to the file. There are two types of redirection operators:> and >>

When we use > operator then the command output goes into the file. but if there is already some data in the file then it will be overwritten.

For example,

ls> output.txt (Syntax: Command> Filename) 

This will save the output of the ls command in the output.txt file. It is already contains some data then it will get overwritten.

If we use >> operator. For example:

ls >> output.txt (Syntax: Command >> Filename) 

Everytime we execute this command the ouput of the command will be get appended to the output.txt.

Keep in mind that if your command generates an error, it will not be saved in the file. If you want to save that error or error message also in the file, then add 2>&1 in your command.

For example,

ls > output.txt 2>&1

Method 2: Use tee command to display the output and save it to a file as well

The output of the command from the redirection operator goes into the file, but it does not appear on the screen.

By using the tee command via pipe, you can not only save the output of the command in the file but can also see it in the screen at the same time.

Its syntax will be:

command | tee file.txt 

For append mode you can use -a operator.

command | tee -a file.txt 

For example

ls -lh | tee output.txt 

More Articles Like This

Exit mobile version