Shell basics: Pipes and redirection
[link—standalone]Every (UNIX) process has (at least) 3 communication channels available to it: Standard input (STDIN), Standard output (STDOUT) and standard error (STDERR). These are initially inherited from the parent process, so the child process does not necessarily know where they lead. These can connect to a terminal, a file, a network connection or a channel belonging to another process.
Symlinks
Stdin, stdout, stderr are presented as files and are actually symlinks to /proc/self/fd/{0,1,2}, directory listing from /dev:
$ ls -la /dev/{stdin,stdout,stderr}
lrwxrwxrwx 1 root root 15 Jul 27 13:36 /dev/stderr -> /proc/self/fd/2
lrwxrwxrwx 1 root root 15 Jul 27 13:36 /dev/stdin -> /proc/self/fd/0
lrwxrwxrwx 1 root root 15 Jul 27 13:36 /dev/stdout -> /proc/self/fd/1
STDIN, STDOUT and STDERR are in fact guaranteed to correspond to file descriptors 0, 1 and 2. Normally in interactive terminal sessions, STDIN reads from the keyboard and STDOUT and STDERR write their output to the terminal window.
Symbols
- < Connect command's STDIN to the contents of a file
- > Redirect STDOUT to file, replace existing file contents
- >> Redirect STDOUT to file, append to file
- 2> Redirect STDERR
- &> Redirect both STDOUT and STDERR (From `man bash`: There are two formats for redirecting standard output and standard error: &>word and >&word of the two forms, the first is preferred. This is semantically equivalent to >word 2>&1)
- | Connect STDOUT of one command to STDIN of another
- && Execute second command if only if the previous command succeeded
- || Execute second command if only if the previous command failed (as in exited with a non-zero status)
An example of use of redirection to avoid spammy "Permission denied" output:
find / -type f -name test 2>/dev/null