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.
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.
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)
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.
Its syntax will be:
command | tee file.txt
For append mode you can use -a operator.
command | tee -a file.txt
ls -lh | tee output.txt