1

Just trying to redirect stout to stderr. But I'm a little confused about these two commands.

echo test 2>/dev/null 1>&2
echo test 1>&2 2>/dev/null

I don't understand why the second one doesn't work properly.

bob dylan
  • 1,832
  • 3
  • 20
  • 31
  • 3
    Because the order of redirections matters. –  Oct 10 '19 at 14:57
  • I expected the first one to be a problem. Are the arguments read from right to left there ? – bob dylan Oct 10 '19 at 14:58
  • @bobdylan The first one is not a problem, but it's also not the usual way to write it. One ordinarily does `>/dev/null 2>&1` – Kusalananda Oct 10 '19 at 14:59
  • 1
    so is `echo test 1>&2 2>/dev/null` working a little like `echo test 1>&2;echo test 2>/dev/null` – bob dylan Oct 10 '19 at 15:01
  • For an in-depth-explanation see https://mywiki.wooledge.org/BashGuide/InputAndOutput#Redirection – markgraf Oct 10 '19 at 15:07
  • 1
    think of a redirection as of a variable assignment. `2>/dev/null 1>&2` is `err:=/dev/null; out:=err`, and `1>&2 2>/dev/null` is `out:=err; err:=/dev/null`. After the 1st, both `out` and `err` will be `/dev/null`, and after the 2nd, `err` will be `/dev/null`, but `out` will be whatever `err` was before the operation (eg. a handle to your tty) –  Oct 10 '19 at 16:54
  • `echo test 1>&2;echo test 2>/dev/null` is the same as `echo test >&2; echo test`, and unlike your 1st example (which does not print anything at all), will print `test` _twice_, once to stdout and once to stderr ;-) –  Oct 10 '19 at 16:59
  • Think of "&" in front of a filehandle as of a "$" (value of) operator, and ">" as an assignment. 1 is A and 2 is B, both default to /dev/tty, the screen: You get: B=/dev/null A=$B. Both B and A are /dev/null. Second line: A=$B B=/dev/null: The first A=B changes nothing. And A is unaffected if B changes later. –  Oct 10 '19 at 20:58
  • @bobdylan I wrote an answer in the https://unix.stackexchange.com/questions/84279/is-this-a-typo-in-bash-manuals-redirection-section. Title is "duplication?". Now you have fifteen answers. Some are good. Check mine it's special. –  Oct 10 '19 at 23:24

0 Answers0