0

Why does the following output redirection result in two lines being printed?

The >&2 copies stdout to stderr and >/dev/stderr also redirects stdout to stderr.

I expect only a single output line as echo foo output is redirected to stderr.

Why don't I see two output lines for: echo foo >/dev/stderr 2>&1 and echo foo >/dev/stdout 2>&1?

➜  app git:(python3.10-pipeline) ✗ echo foo >/dev/stderr >&2
foo
foo
➜  app git:(python3.10-pipeline) ✗ echo foo >/dev/stdout >&2
foo
foo
4
  • I only see one line.
    – choroba
    May 22, 2023 at 12:44
  • @Kusalananda I also don't believe that the part about copying stderr to stdout (>&2) (which is mentioned in the original question both in the title and the body) is just a typo, but rather that the OP is actually confused about what get's redirected/copied where. Hence my (now deleted) answer. May 22, 2023 at 13:31
  • @MartinHeralecký, that might be part of it, but it doesn't really explain the duplication either way
    – ilkkachu
    May 22, 2023 at 14:03
  • @MartinHeralecký I took the duplication as the main issue and the mixup about the redirection here or there as a misunderstanding. The question is "why is the output duplicated?".
    – Kusalananda
    May 22, 2023 at 14:32

1 Answer 1

5

In the bash shell, redirecting the same stream twice will result in the stream's contents being redirected to the last (rightmost) destination. It is true that if you were to give the bash shell the commands that you show, only a single line of output would be generated by each (on the standard error stream).

However, you use the zsh shell, not bash. In the zsh shell, by default, the shell will treat multiple redirections of the same stream as a request to duplicate that stream, as if tee had been used.

This means that

echo hello >/dev/stderr >&2

or

echo hello >file1 >file2 >file3

which redirects standard output two and tree times, respectively, will duplicate the standard output stream in the same way that

echo hello | tee /dev/stderr >&2

or

echo hello | tee file1 file2 >file3

would do.

You can disable this behaviour by unsetting the MULTIOS shell option in the shell (unsetopt MULTIOS).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .