Redirecting Output (STDIN or STDERR)

There are 3 file descriptors, stdin, stdout and stderr (std=standard).

Any program you run from a shell will have 3 file descriptors:

- STDIN, or standard input - if running interactively, this will be whatever input you give it via the keyboard. STDIN could also be the output of another command being piped in. This is file descriptor 0. - STDOUT, or standard output - this is where most of the messages the program writes out will go. If the program was started interactively, this will go to your console unless you direct it elsewhere. This is file descriptor 1. - STDERR, or standard error - error messages go here. As with STDOUT, this will normally go to your console. This is file descriptor 2.

Piping between programs

You can easily pipe the output of a program into another, for example:

$ cat file.txt | sort | uniq

In the example above, the STDOUT of the cat command is fed to the STDIN of the sort command, and the STDOUT of the sort command is in turn fed to the STDIN of the uniq command. The STDOUT of the uniq command will go to your console, as it hasn't been sent anywhere else.

Redirecting to a file

Let's say we want the result of that last example written to a file.

cat file.txt | sort | uniq > file2.txt

There, it's as it was before, except the STDOUT of the uniq command is now directed into the file file2.txt instead of going to your console.

Or, maybe you only want errors to go to the file, not the normal output?

mycommand 2> errors.txt

That will send only STDERR to the file.

Redirecting to another file descriptor:

If you want to redirect STDERR (fd 2) to STDOUT (fd 1), use:

mycommand 2>&1

The above snippet will redirect STDERR output to STDOUT.

Redirecting STDOUT and STDERR to file

Perhaps you want both STDOUT and STDERR to go to the same file?

mycommand &> myfile.txt

The above will send both STDOUT and STDERR to a file.

However, you cannot use ''&»' to append to the file.

You must use something like:

# this will work
ls -yz >> command.log 2>&1

# but it *won't* work like this:
ls -yz 2>&1 >> command.log

As you see, if redirecting both stdout and stderr, the order of the commands makes a difference.

Of course, sometimes you don't want the output of a command, so you can just redirect it to /dev/null instead.

 
bash/redirectoutput.txt · Last modified: 2010/02/26 10:45 (external edit)
 
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki