06. Redirection standard in, out, err

Three directions

There are three directions on the command line..

standard in
Sending input into a program.
standard out
Normal output that comes out of a program.
standard error
Error outputs when there are problems in a program.

1) Standard In

Let's pretend we have some java program that reads in some words, then outputs them. We can run this program by typing the words ourselves (as arguments). Or we can redirect a file to be the standard input.

$ java test < testInput.txt

This would send the the text in helloWorld.txt as the inputs.

2) Standard Out

When running a program or command, the normal output will appear on the terminal - this is known as the standard out.

To redirect standard out to a file, we use >. So instead of outputting our standard out to the screen, it will store it in a file called lsTestOutput.txt. In case we don't want to overwrite the existing contents of lsTestOutput.txt, we can use >> instead of >.

$ ls -l > lsTestOutput.txt

3) Standard Error

To redirect standard error, we use 2>

$ java notARealProgram 2> errorMessage.txt

Since notARealProgram isn't a real program in our case, this will result in an error that gets directed to errorMessage.txt.

To redirect both standard error and standard out together, use &>.

Using standard in and out together

You can use both standard in and out notations in case you need to input some arguments, and would like to output to a file.

$ java test < inputFile.txt > outputFile.txt

To specify one file as both the standard input and output, use <>.

$ java test < inAndOutFile.txt 

Please send all complaints to /dev/null

/dev/null is a special folder that acts like a trash bin (nothing gets saved there).

If you want to suppress error messages, you can direct your standard error to /dev/null.

$ java notARealProgram 2> /dev/null

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Take your Linux skills to the next level!

Command Line Kung Fu

Take your Linux skills to the next level! Try Linux & UNIX

Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.

$ Check price
14.9914.99Amazon 4.5 logo(27+ reviews)

More Linux & UNIX resources

Ad