Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

|& pipes both


Yes! And |& is so much easier to remember than 2>&1 or is it 1&>2?!

I'm sure there's some obscure reason why |& isn't the one people suggest first but when I learned about it recently it was hugely useful.

(And if I haven't learned the correct ordering for the > variant by now I think it's fair to assume I was never going to do so...)


> I'm sure there's some obscure reason

|& isn't POSIX. As for the redirection order, if you haven't learned it yet, learn now!

These numbers arent magic. 0 is stdin, 1 is stdout, and 2 is stderr. These are the free file descriptors you get on Unix and on Windows. Stdout (1) from previous process goes to stdin (0) in the next process in a pipeline. So, if you want less to see the previous processe's stdout (1) and stderr (2), you just need to tell shell "send stderr to wherever stdout is going right now". That's exaxtly what 2>&1 means.

A fun caveat about this syntax is the difference between these two:

    ls >/dev/null 2>&1
    ls 2>&1 >/dev/null
The first one tells stderr to go to dev null ("where stdout is going right now"), and the second one sends stderr to the next process and stdout to dev null


> > I'm sure there's some obscure reason

> |& isn't POSIX

POSIX, the obscurest of reasons! :)

While I appreciate you taking the time to explain the details, it's not that I haven't tried to learn/remember the specifics but that I tended to use it so infrequently that I'd forget in between uses--and even while knowing the specifics in terms of file descriptors & redirection syntax I would claim the ampersand placement/usage isn't exactly intuitive.

Also, my use primarily tends to be interactive rather than scripting so POSIX compatibility is less of a concern than whether I have to think about it--if I end up somewhere POSIX-compliant that isn't also bash clearly I took a wrong turn and should just through the whole computer out the window. :D

It might be a weird & non-POSIX pipe to die in but at least it's mine. :)

EPIPE


It didn't exist until "recently", but my mnemonic for 2>&1 is two goes to one, but not just one, but to the same place as one, so you have to dereference it with an ampersand.


Thanks for sharing, now I think I can't remember either approach. :D

But I'm glad the mnemonic works for you. :)


The problem with this is it just merges both. I want to be able to pipe both while keeping them separate.

I guess at that point you'd need 4 standard FD's: STDIN, STDOUT, STDERRIN, and STDERR.


wait what? in what shell? (since that’s not POSIX)




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: