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

make 2>&1 | head (or less) is a common occurrence in my .bash_history :(


I actually have this written on the corner of my whiteboard because I can never remember bash's syntax for piping out stderr!


If you don't mind being bash-specific, you can shorten 2>&1 | to just |& .


Good lord. I think you just changed my life.


Similarly &> works for redirecting both stderr and stdout to a file. >& is the alternate, less preferred syntax.


Perhaps it will help you to understand some background:

In a Unix process stdout typically is file descriptor 1 and stderr is fd 2. So you are saying: Redirect from fd 2 into fd 1.


The biggest problem is mixing up >& and &> ...which ends up leaving a bunch of files called "1" around with a runaway background process :(


Yeah, it's tricky. I remember it by breaking it into two pieces. "2>" means redirect stderr (file descriptor 2) to the following token. "&1" is the token for stdout (kinda like the address-of operator). So taken together, "2>&1" means redirect stderr to stdout.

Bash-only shortcuts like &> don't improve the situation :)


The phrase "two greater amper one" seems to help me. My tendency otherwise is to type the ampersand before the greater-than.




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

Search: