EXPLAIN: Redirection
Recirection is a technique that can be used with command line applications in most (all?) Unix-like operating systems. There are three standard interfaces that any command line application can make use of: the standard input, the standard output, and the standard error. We’re not going anywhere near the standard error today, but the other two are important to the concept of redirection.
The standard input is where an application expects input to come from. In a practical sense, the standard input is almost always the keyboard.
The standard output is where an application expect to write its output during execution. In real life, the standard output is almost always the screen (although writing output to a file - such as log files - or a printer isn’t *that* uncommon).
Now that we have those two concepts down, the premise of redirection is simply redirecting the input or output away from the standard input or output in such a way that the application is unaware this redirection is occuring. Most Unix-like applications don’t really care where they get input from or write output to.
The most common redirection operators are the greater-than and less-than signs <>.
As an example of redirecting the output, consider the ls command. By default, the ls command enumerates the files in the current directory and writes them to the screen. However, using ls > ls.txt will redirect the output to the file ls.txt. You will not see any output on the screen (you can have both, but that’s another command we’ll talk about in a later post). To see the output of you ls > ls.txt command, use your favourite text editor to open the ls.txt file and take a look.
As an example of redirecting the input, consider the command Mail -s “Testing Redirection” someuser < ls.txt. You’ve likely never used the Mail command from the command line as most home users don’t have much of a use for it, but the Mail command by itself will prompt you for, amongst other things, text for the message body. In this case, instead of typing the message in from the standard input, we are redirecting the input to our ls.txt file. This command will send our ls.txt file to someuser as the body of the email.
As with many GNU/Linux commands, redirection opens up an absolute wealth of possibilities. Talk amongst yourselves…
Related Stories
POSTED IN: Explanation
1 opinion for EXPLAIN: Redirection
Antonio
Feb 28, 2007 at 2:53 pm
Very nice site! Good work.
Have an opinion? Leave a comment: