When we run a command on a terminal on Linux it generates some output of that command. Sometimes we need the output result of the commands. Today we are going to see how to save the output of the command.
Using Redirections in Linux:
We can use the redirections operators to save the output of commands into files. Redirection operators redirect the output of a command to the file instead of the output terminal.
There are two main redirection operators in Linux:
The first operator is “>” which is used to redirect the output of a command to the file, but this operator erases all existing data in that file and overwrites the command output,
Let’s see one example of > redirection operator:
In the above image, we can see that the previous content of the output.txt file gets erased and the output of the ls command is written into the file.
Now let’s see about the second redirection operator is >>. Using this operator we can append the output of the command to the file. It does not erase any previous content of the file.
Let’s see the example of >> operator
In the above image, we can see that the output of the command is appended to the output.txt file without erasing the content stored in that file.
If the file mentioned after the Redirection operator in not exist then it will create automatically.
Using tee command:
When we use the redirection operator the output is going to the file only the redirection operator does not print it on the terminal. To see the output on the terminal and also save it into the file we can use the tee command. It sends the output of the file as well as to the terminal.
First, let’s see how to use the tee operator using the pipeline. Following is the syntax of using the tee operator:
command | tee outfile.txt
Now let’s see one example of the tee command:
We can see in the above image the output is redirected to the terminal as well as the output.txt file.
To append the output of the command to the file use the –a option with the tee command. Here is the syntax of the command:
command | tee outfile.txt
Now Let’s see one example of this command
In this image, we can see that the output of cowsay command is stored in the output.txt file without erasing the existing data of the file.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!