An example in practice. The bookβs original explanation is an exact description of what the POSIX standard says, but I have POSIX-friendly shells ( bash
and dash
, the only ones that I think are common on Linux) are not picky.
The POSIX standard says the same thing as the book on input and output descriptors, and continues this: for n<&word
, "if the numbers in the word
do not represent a file descriptor that is already open for input, then a redirect error occurs." Therefore, if you want to be careful about POSIX compatibility, you should avoid this use.
The bash documentation also says the same thing about <&
and >&
, but without the promise of an error. This is good, because in fact it does not lead to an error. Instead, empirically, n<&m
and n>&m
seem to be interchangeable. The only difference between <&
and >&
is that if you leave the fd number on the left, <&
will default to 0 (stdin) and >&
to 1 (stdout).
For example, run the shell with fd 1, pointing to the bar
file, then try the exec 4<&1
example for sure, try writing to the resulting fd 4 and see if it works:
$ sh -c 'exec 4<&1; echo foo >&4' >bar; cat bar foo
This executes, and it executes using either dash
or bash
(or bash --posix
) for the shell.
Under the hood, this makes sense because <& and> & is almost certainly just called dup2 () , which doesn't care if fds are open for reading or writing or adding or what.
[ EDIT : added POSIX link after discussion in comments.]
source share