Command line fundamentals - redirect a command’s output to a file

This is a pretty basic command line tip, but if you're new to all this CLI goodness, you might not be aware of it.

When you run a command normally, the output from that command gets sent to the terminal you're working on, so you can see what happened. Sometimes, though, this isn't what you want to do.

All modern command line shells support something called redirecting. This is where you instruct the command line to run a command, but then redirect all the output from it to a file (or if you get into pipes, into another program, but that's for another day).

You can achieve this by using the following notation:

$ ls > file

In this case, ls is the command and file is where we want the output sent to. As you might expect, the results of running ls are going to be dumped into the file you specified.

There are a couple of other things you can do as well. The > notation will overwrite the target file if it already exists. To avoid this and to append to the given file, use a double arrow, like >>.

$ ls >> file

Finally, any errors or system messages may still appear on your terminal when you redirect the output of your command. This is because this information is sent to the stderr output instead of the stdout output (which is used for normal output).

To catch stderr messages too, use the 2> notation.

$ ls / >> file 2> errors

Obviously, if no errors occur, nothing will be written to the file. You can use the same file for catching normal output and messages if you use the append operator properly.
$ ls / >> file 2>> file

In fact, you can also do other stuff with command redirection, such as use the arrows the other way when necessary, but I think that's more than enough for today. :)

Avatar for peter Peter Upfold - http://peter.upfold.org.uk/

Peter Upfold is a technology enthusiast from the UK. Peter’s interest in Linux stems back to 2003, when curiosity got the better of him and he began using SUSE 9.0. Now he runs Linux Mint 9 on the desktop, runs a CentOS-based web server from home for his personal website and dabbles in all sorts of technology things across the Windows, Mac and open source worlds.

Home » Articles »

Discussion: Command line fundamentals - redirect a command’s output to a file

  1. lee doolan (guest)

    # Posted on 17 June 2007 at 11:48 PM

    You have got to be s**tting me! This is worthy of a front page post?



Home » Articles » Command line fundamentals - redirect a command’s output to a file