2

I have been reading about bash redirection, and encountered those two articles about it

how come >&file make file a file descriptor

  • Note that the string file is not an integer. So >&file would not somehow be interpreted as >&n where n is some integer value (as in >&1). – Kusalananda Oct 16 at 5:11
4

It's actually two different operators which conflict with each other, one from the Bourne shell, one from the C shell.

cmd >&2

Short for

cmd 1>&2

Is the Bourne shell operator that runs cmd with its stdout (fd 1) connected to the same resource (same open file description) as that on fd 2 (x>&y (or x<&y which is exactly the same) redirects fd x to the same resource as on fd y).

cmd >& file

Is the C shell (csh) operator that runs cmd with both its fd 1 and 2 connected to a new open file description obtained by opening file in write-only mode. In Bourne shell syntax, the equivalent would be cmd > file 2>&1

They do conflict. Which one is actually used depends on whether the target is numerical or not.

If you have:

cmd >&"$file"

The Bourne shell operator will be used if $file contains a sequence of decimal digits and the C shell operator will be used otherwise!

That's why it's better to avoid that csh operator and use the Bourne shell syntax (> file 2>&1) instead.

bash (and zsh) also has a &> operator as an alternative to >&, but note that it breaks POSIX compliance as cmd &> file is meant to run cmd & and then > file in POSIX sh. It does however not have the conflict problem mentioned above.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.