&
is the prefix you give to file descriptors the shell has open, as opposed to the paths of unopened files (which is the default). STDOUT
is almost always file descriptor 1
and STDERR
is almost always 2
.
For the angle bracket, your shell is usually smart enough to know any number preceding it is going to be the file descriptor. If you omit one it usually assume you're talking about STDOUT
for >
and STDIN
for <
.
So putting it together:
# command > /tmp/myFile
# command 1> /tmp/myFile
Both direct command
's STDOUT
to the flat file called /tmp/myFile
# command >&2
# command 1>&2
Both direct command
's STDOUT
to the already opened file at file descriptor 2
(STDERR).
# command 2>&1
Redirects anything that would normally be written to STDERR
to file descriptor number 1
(STDOUT
).
These are generic to any sort of file I/O you do from the shell itself. It's just that the specific file descriptor in question themselves usually have special meaning.
If you wanted you could redirect STDERR
to a file you could also tell it to assign file descriptor 2
to a named file:
# command 2> /tmp/newFile
For example:
[root@edc4 ~]# ./causeError 2>/tmp/containError
[root@edc4 ~]# cat /tmp/containError
Error Message
[root@edc4 ~]#
The Bash HOWTO goes into a lot more detail of how to work with file descriptors in bash
. You can open files underneath file descriptors other than the usual three (0
, 1
, and 2
) but that's usually reserved for more elaborate scripts and people generally only deal with the usual three. Even then, it's usually just 1
and 2
people deal with.