Monday, April 4, 2016

Redirect Command Line Output to Files in Linux

When using a Linux shell, often you'll find it useful to write the output of a command to a file instead of to the screen. This could be to edit a configuration file or simply to save the output for later use. There are a couple of ways to do this and each has its use.

To redirect output to a file, you can use the carrot (>). Keep in mind, this will overwrite the file if it already exists or create the file if it does not already exist.
$ echo "Hello world!" > ~/output.txt
$ cat ~/output.txt 
Hello world!


If you use the carrot (>) again to write something to the same file, the original contents will be overwritten (I know I said this twice, that was deliberate). If you want to keep the contents of an existing file, you can use the double carrot (>>) to append the output at the end of the file. The double carrot (>>) will also create the file if it does not already exist.
$ echo "Hello again world!" >> ~/output.txt
$ cat ~/output.txt 
Hello world!
Helo again world!


If you want to write the output of a command to both the screen and to a file, use the tee command. By default tee will overwrite an existing file if it exists and create the file if it does not exist.
$ echo "Hello world!" | tee ~/output.txt
Hello world!
$ cat ~/output.txt 
Hello world!


When using tee, if you want to append to the end of an existing file instead of overwriting it, use the -a flag.
$ echo "Hello again world!" | tee -a ~/output.txt
Hello again world!
$ cat ~/output.txt 
Hello world!
Helo again world!


No comments:

Post a Comment