If you are running the BASH shell on your Linux or Unix system then you can utilize these redirection examples. There are many ways to redirect input and output from the bash shell environment. This article will outline how to redirect stderr, redirect stdout and how to redirect stderr to stdout.
Other articles about Bash:
In BASH, 1 represents stdout or (standard output) and 2 represents stderr or (standard error). This is useful from a C binary when using fprintf to send error data to a specific file and normal output data to another.
1. Standard Output (stdout) To A File
This is the most common usage of Bash redirection:
$ cat data.txt > new_file.txt
All standard output from our cat’ing of the file will end up in new_file.txt.
2. Redirect Standard Error (stderr) To A File
To redirect stderror to a file we must use the numeric definition of standard error.
$ cat data.txt 2> output_error.txt
This will populate the file with standard error material.
3. Send Standard Out (stdout) And Standard Error (stderr) To A File
To send both standard out and standard error to a file we can use &> for redirection.
$ cat data.txt &> all_output.txt
4. Standard Error (stderr) To Standard Out (stdout)
It is sometimes useful to store both standard output and and standard error in the same place, but sending it through standard out. Using 2>&1
$ cat data.txt 2>&1 output.txt
5. Redirect All Output To The Bit Bucket In The Sky
To redirect all output to a sink hole, we can redirect to /dev/null.
$ cat data.txt &> /dev/null
In my examples I used cat, but you could use any program or shell script that outputs data. All redirection is processes by the BASH shell.