Login | Sign up

May 28


0

Save the output of commands

Comments (0)

There are many reasons you may want to save the output of various commands. You may be establishing a baseline, documenting, keeping records, or just manipulating existing files. Learn how to do it and learn about saving errors too.

You can save the output of most Linux commands to files using output redirection. All you need to do it is add a greater than symbol at the end of the command and a file name to save to.

  1. netstat -na > <file>

Caution: this will overwrite the file you are sending the output to.

Appending output

In order to have the saved output appended to the end of the file without overwriting it, simply put two greater than signs.

  1. netstat -na >> <file>

Saving errors to files

The previous examples with only save the normal output to files. Any errors are typically sent to something call standard error. You can save these errors to files just like saving the output using a slightly different syntax. All you need to change is to add a 2 before the greater than sign(s).

  1. grep localhost /etc/* 2> myerror.log
  2. grep localhost /etc/* 2>> myerror.log

When running the previous example as a normal user, you should get several errors about permissions. The first example will save all the errors to the file myerror.log and overwrite anything previously in the file. The second example will do the same thing except it will append the errors to the file without overwriting it.

Saving output and errors

You can save the output of a command to a file and the errors of the same command to a different file

  1. grep localhost /etc/* >> myfile.log 2>> myerror.log

It is possible to save both the output and errors to the same file using the following example.

  1. grep localhost /etc/* >> myfile.log 2>&1

The number 2 is the file descriptor for standard error and the number 1 is the file descriptor for standard output. Putting 2>&1 at the end of the command (after having redirected the output) is simply saying send standard error to the same place as standard output.

Tags:

Comments

There are no comments yet.


Post a new comment

Note: Items marked * are required fields

Post a comment

You must login before you can do that.

If you don't have an account, register for free. It's completely private.

Why register

  • rate posts and comments
  • ask questions about posts
  • request new topics/tutorials
  • mark posts as favorites to easily find them again