Terminal is used to run different types of Linux commands. Sometimes the output of these commands require for various purposes. There are multiple ways in bash to redirect or save the commands output into a text file. One way is to use > or >> operator for redirecting command output into a text file. But one of the limitation of this technique is that it only saves the command outputs not the commands. But if you want to save all the outputs with commands then you can use other bash command called script. The use of these two ways are shown in this article with examples.

Using Redirect Command

Press Ctrl+Alt+T to open the terminal. Suppose you want to save the output of the command ls -la. Type the command as,

$ ls -la > output.txt

The new output.txt file will be created in the current location and the output of the ls -la command will be stored in this file. Now open output.txt file and you will see that the content of the file is same as the output of ls -la command.

When you want to store multiple commands output in a single file then the last command will overwrites the previous output every time if you follow the single redirect operator. To solve this problem you can use double redirect operators to append the new command output at the end of the output file. In this way you can save multiple command outputs in a single file. If you want to append the output of pwd command then run the command in the following way.

Now open output.txt file to check the output is appended or not.

Using Script command

You can only save the command output by using redirect operator. The output file doesn’t keep any record of the command that is associated with output. It is important to record the output with command also to understand the output properly. You can use bash script command to solve this problem. If you type script before running any command then the script session will be started by creating a default file name. If you want to set specific file name to record the script then type the file name with the script command. In the following example, file name is set as command_output.txt.

$ script command_output.txt

Now type those commands that you want to save in the script file. In the following example, ls command is executed to record in the script file. Type exit to stop recording of command output into the script file.

Type the following command to show the content of the command_output.txt file. The output of the full script session will be shown in that file from script start to script end. It is easier to identify which output is associated with which command from the recorded script.

$ cat command_output.txt

Sometimes you need to share commands and outputs with other user for many purposes. You can easily do that task by following above steps.

You can show all steps by clicking on the following video link.


Please enter your comment!
Please enter your name here