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

  • June 14, 2007
  • Avatar for peter
    Peter
    Upfold

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

Home » Articles »