In this tutorial we will talk about redirection of standard streams, stdin, stdout, stderr in Unix-like operating systems. The Unix philosophy is to write programs that do one thing, but do it well and write them to work together, so the output of a program can be used as input to another, this is great because we can transfer data continuously from a program to another without manually feeding data into each one.
A real life example of the diagram 1.0 using the ps and grep commands.
The psaux will show every process running on your system, while the grepbash will print the lines that matches the “bash” string. The pipe operator “|” will feed the output of the ps command (stdout) into the input of the grep command (stdin), so the result will be every process that includes the “bash” string.
The result is not what we might expect, because we used grep to match only the lines with the “ipv4” string. The explanation is that the lines containing the “Permission denied” string don’t reach the grep command, they are errors which by default goes to display, through the stderr stream (see diagram 1.0). This example can be fixed by redirecting the stderr to stdout using the redirection operator “>“.
find /proc -name ip_forward 2>&1 | grep ipv4
Back to the basics.
Standard streams can be found in many environments, shortly they are input and output connections between a process and a device or pseudo-device. Each stream is mapped to a file descriptor (FD), a non-negative integer assigned by the operating system. Linux and Unix handles the IO using three streams, check out the table from below.
The program reads data from a physical device, usually a keyboard or redirection.
Where a program writes its output data.
Where a program writes its error messages.
Redirect to another program via pipeline, run the commands as normal user.
| Redirect stdout to grep'sstdin, stderr goes to display.