1

When I run 1>&2 echo hi |& grep hi, I get a non-colored hi followed by a red hi on a new line. This is the same output as 1>&2 echo hi | grep hi. Why aren’t both of the “hi”s red in the former?

1

Your first pipeline:

1>&2 echo hi |& grep hi

This is the same as

echo hi 1>&2 2>&1 | grep hi

since |& is the same as 2>&1 |.

With the MULTIOS shell option set, this would duplicate the output of echo to standard error. This produces the un-coloured hi that grep never sees. The other hi goes through grep and is coloured.

The 2>&1 redirection does not do anything as there is no output to standard error from echo. It would be different if you had e.g.

{ echo hi 1>&2; } 2>&1 | grep hi

or

{ echo hi 1>&2; } |& grep hi

where the standard output from echo would not be duplicated and the standard error of the { ...; } would have been sent to grep, producing a single coloured hi.

Your second pipeline,

1>&2 echo hi | grep hi

or,

echo hi 1>&2 | grep hi

(which is the same as your first pipeline with the no-op 2>&1 redirection removed) also redirects standard output twice; once to standard error (the un-coloured hi), and to the pipe (the coloured hi).

For two coloured hi's:

echo hi 2>&1 1>&2 | grep hi

or

echo hi 1>&1 | grep hi

(This is with a tiny bit of handwaving as I'm not quite used to the zsh shell)

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.