Linux Commands

How to Redirect the Output of a Command to a File in Linux

Whenever we run a command on a Linux terminal, its output is usually displayed on the terminal as soon as the said command finishes its execution. However, at times, we might want to save this output somewhere else to use it later on. Therefore, today, we will show you the different methods through which you can redirect the output of a command to a file in Linux Mint 21.

Methods of Redirecting the Output of a Command to a File in Linux Mint 21

To redirect the output of a command to a file on a Linux Mint 21 system, the two most commonly used methods are shared in the following:

Method #1: Using the “>” Operator

You can use the following command to redirect the output of a command to a file in Linux Mint 21 without displaying the output on the terminal:

$ ls > output.txt

This command redirects the output of the “ls” command to a file named “output.txt” without displaying anything on the terminal as shown in the following image. If the “output.txt” file is already present in your system, this command simply overwrites its contents. Otherwise, it will first create this file and then save the output of the “ls” command to this file.

Now, to confirm whether the output of our command has been redirected to this file or not, we use the following command:

$ cat output.txt

This command displays the contents of this file which is in fact the output of the “ls” command as shown in the following image:

Method #2: Using the “tee” Command

If you wish to redirect the output of a command to a file in Linux Mint 21 while also displaying that output on the terminal, you have to use the following command:

$ ls | tee result.txt

The output of this command is shown in the following image:

However, to confirm if the output is also redirected to a file or not, we run the following command:

$ ls

This command tells us if an output file is created within our current working directory or not from which we will be able to verify the redirection of the output of our command. You can see in the following image that an output file named “result.txt”is successfully created.

You can get further confirmation by looking at the contents of the “result.txt” file with the help of the “cat” command as we did in our first method.

Conclusion

By picking any of the two methods that are explained previously, you can easily redirect the output of a command to a file in Linux. In this guide, we used the “ls” command for the sake of demonstration. However, you can redirect the output of any command of your choice to a file in Linux Mint 21 by making use of these methods.

Similar Posts