While working in the terminal output of commands are shown directly in the terminal window.But there are times when you need to save the output of a command to a file to work with it later like important data to analyze, compare, troubleshooting etc. So, working in Bash you have the ability to save the displayed information from a Terminal window to a text file. Let’s look at how it’s done.
Option 1: Just Save the Output of Terminal Command to a File
In this case, the entire result of any command will be written to a text file, without displaying it on the screen. We save the output information to a file directly. To implement this, you need to use the operators
> saves the output to the specified file, and if, it already has information, it will overwrite it.
>> will save the output to a file, and if, it already has information, new data will be added to the end of the file.
Consider for example the command
ls, which displays a list of files and folders in the specified directory. Let’s write the output of this command to a text file. We need to write the command with the required operator and specify a file path:
ls > see.txt
Now let’s see if everything worked. You can use any text editor, which you have. It can also be done directly in the terminal using the
[email protected]:~$ ls > see.txt [email protected]:~$ cat see.txt feb.gif ghost.img jan.jpg march.jpg see.txt [email protected]:~$
Tip: Remember that
> will overwrite all data in the file, so if you need to add something to a file, use the operator
Let’s say that after we have saved the result of
ls in the file “see.txt” we decided to save the version of the kernel while using the same file. To find the version of the kernel use
uname and option
-a, then specify the file to save the result of its output:
uname -a >> see.txt
Again check the result:
[email protected]:~$ uname -a >> see.txt [email protected]:~$ cat see.txt feb.gif ghost.img jan.jpg march.jpg see.txt Linux host.datacenter.com 4.8.0-37-generic #39-Ubuntu SMP Fri Mar 9 21:02:39 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux [email protected]:~$
As you can see, we have preserved the work and
Option 2: Save output to a file and display it on the screen
It is not convenient all the time to use operators
>> because sometimes its better to show the output of a command on screen and save its output to a fill too. In this case, we can use the
tee, which displays the execution of commands on the screen and save it to a file. Its syntax is as follows:
ls | tee see.txt
This option is similar to the operator
>, i.e. when writing output to a file, all the old data will be deleted. If you need to append to a file, you must add the design
ls | tee -a see.txt
In Bash there are multiple operators and commands perform identical tasks, they are often used in different scenarios, but for the average user these comamnds are quite enough.