Redirecting output is one of those things that's super simple, but not well known. Here's how it works.
Your typical "hello world" program writes to the console aka command shell. Depending on your language, it might be something like:
//C#
Console.WriteLine("Hello world");
//Java
System.out.println("Hello world");
//C++
cout<<"hello world\n";
//etc
print "Hello world"
You can
redirect this output using a greater than sign. Think of it as sending the output somewhere else.
dir > output.txt //output the result of "dir" to the file "output.txt"
likewise, two greater than signs will
concatenate:
echo "hello" > output.txt
dir >> output.txt
Incidentally, you can do severe damage with this in Linux, where everything is exposed as a device, including your hard drive:
cat /dev/random > /dev/hda1 Oops!
... but that's another story.
Now, when it comes to redirecting output, things get slightly more interesting when you realize that standard output is being written to your console -- "stdout", but errors are also written to the console. Normally, you'd never know the difference.
But you can
selectively redirect standard output versus error output by being explicit. Here's an example of writing to both stdout and stderr in C#:
using System;
class StdErrTest{
public static void Main(){
Console.WriteLine("Hello stdout ...");
Console.Error.WriteLine("Hello stderr ....");
}
}
here's what the output looks like:
> mono StdErrTest.exe
Hello stdout ...
Hello stderr ....
It all looks the same, but you can selectively redirect these using the greater than symbol with
2 for error and
1 for standard output:
> mono StdErrTest.exe 1>> output.txt
Hello stderr .... //(standard output was redirected to a file)
> mono StdErrTest.exe 2>> error.txt
Hello stdout ... //(error was redirected to a file)
In this quick example, we're redirecting the output of stdout, and concatenating it to a file, but stderr still gets printed to the screen. Likewise in the second case: we're redirecting stderr to a file, but letting stdout print to the screen.
You can combine redirection in various ways:
> mono StdErrTest.exe 2>1&> output.txt //(Redirect both stdout and stderr to a file)
> cat output.txt
Hello stdout ...
Hello stderr ....
I used Mono on Linux for the example, but it's basically the same with any dos shell (cmd).