Redirection Operators for Testers
Redirection operators (|, >, >>, <) let you chain Unix commandline commands together, and move information in and out of the chain.
|chains commands i.e. sends the output of one to the input of the next. More precisely, it sends the stdout of one the the stdin of the next, sending stderr to the terminal.<sends input into commands – so you can (generally)-
doathing < file.txtand < file.txt doathing
-
- which works similarly to the common chain
cat file.txt | doathing >and>>and>&redirects the output. (>overwrites a file while>>appends to a file, and>&redirects to a file descriptor – typically a stream).
> has a space before it, it redirects stdout, leaving stderr to throw errors at you in the terminal.> and >> are related,|(pipe) and || (OR) are not.&(file descriptor) and && (AND) are not, either.Outputs and File descriptors
tl;dr 2> sends stderr to a file and >&2 sends an output to stderr
Commands output (what you expect) to stdout, which is typically the terminal window, and (problems) to stderr, which is also the terminal window. These are streams, and they're mixed as they are produced. find's splurge of mingled filenames and permission errors is a perfect example of this.
You can separate and redirect these. stdout is file 1 within the command, so you catch stdout in file.txt with 1> file.txt . stderr is file 2, and you catch stderr in fubar with 2> fubar.
Numbered file descriptors let you refer to these on the output: stdin &0, stdout &1, stderr &2 . Note that while N> means send N somewhere, >N means send to a file called N, and you need >&N to tell the machine to use the descriptor.
Common patterns:
> somethingsends stdout to something, leaving stderr on-screen in your terminal.2>somethingsends stderr to something.2>&1sends stderr to stdout&>somethingredirects both stdout and stderr to something> /dev/nullor1> /dev/nullto throw stdout away,2> /dev/nullto throw stderr away.
curl 's approach to stderr is unusual. If stderr is the terminal (i.e. if you're using it manually) it will report !progress (dynamically)! and errors. If not, (i.e. you're using it within a command) it'll just report errors.The numbers mean...
- 0 represents standard input stdin
- 1 represents standard output stdout,
>is equivalent to1>.&1is equivalent to/dev/stderr - 2 represents standard error stderr.
&2is equivalent to/dev/stdout.
Higher numbers only make sense if they’ve been opened explicitly
More thoughts
What does 2>>&1 do? Nothing: it is bad syntax
While 2>&1 sends errors to stdout, the order is not guaranteed: streams may be interleaved, but one does not overwrite the other.