03. Standard I/O redirection

Standard in, out and error

The idea behind a standard input and output is that there is a data source, a sink and a place to report all errors.

To summarize standard IO:

Standard Input
Used to input data.
Denoted with a < symbol.
Standard Output
Where the normal output goes.
Denoted with a > symbol.
Standard Error
Where all error messages are reported
Use 2>.
Appending
Attaches second file to bottom of first file.
Denoted with a << symbol.

As an example, take this RepeatInput program which reads in an input, then spits it back out.

$ java RepeatInput < "hello world!" > hello_world.txt 
# "hello world!" now stored in hello_world.txt

/dev/null

/dev/null is a special place on our UNIX machine that acts as a trash bin. Anything sent to /dev/null is discarded.

If you want to omit all errors when running a program (which you should have a very good reason to do) then you can simply direct error messages to /dev/null.

#!/bin/bash
# Program runs silently by throwing away error messages 
java ProgramWithErrors 2> /dev/null

You can also run a script that clears files by overwriting its content with /dev/null

#!/bin/bash
 
cd /var/log
cat /dev/null > logMessages
 
echo "Log files all cleaned up!"

Pipelines

There are also pipelines, which are used to take the standard output of one command to be used as the standard input of another command. These commands are joined together by a |.

Pipelines should be ordered so that you reduce the most amount of data on each step.

$ ls | grep .txt | wc -w
# How many files with .txt extension are in current folder
22

Take your Linux skills to the next level!

Linux for Beginners

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

Linux for Beginners doesn't make any assumptions about your background or knowledge of Linux. You need no prior knowledge to benefit from this book. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(101+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Ad