How to Save the Output of the Command Terminal (Bash) to a Text File

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 > and >>.

Operator > saves the output to the specified file, and if, it already has information, it will overwrite it.

Operator >> 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:

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 cat command:

Everything works.

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:

Again check the result:

As you can see, we have preserved the work and ls and uname.

Option 2: Save output to a file and display it on the screen

It is not convenient all the time to use operators > and >> 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:

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 -a

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.

Authored By Imran Yousaf

I am Imran Yousaf, a computer geek, founder of the site Smashinglab.com. I am a die hard fond of open-source software and Linux operating system. In addition to Linux, I am interested in everything related to information technology and modern science.

Leave a Reply

Your email address will not be published. Required fields are marked *