13

Do you have a mnemonic or system? This has bothered me for years I always have to look it up

zzapper
  • 1,140

7 Answers7

20

If you are a C programmer, you can think of &1 as "the address of 1" so 2>&1 reads "redirect file descriptor #2 to the same place as #1".

lgeorget
  • 13,914
3

"Two to and one" ("to" being >) makes more logical sense to me than "Two and to one", which is what I might usually confuse it with. If you consider "and one" as a single noun (a place), it also makes grammatical sense in context, which is harder to do with "Two and to one" -- you'd have to consider "to one" a single noun, and it still would not make contextual sense.

goldilocks
  • 87,661
  • 30
  • 204
  • 262
2

When you write 2>&1, you're saying "standard error goes to standard output".

Let's break that down.

First you want to memorize that standard error is 2 and standard output is 1.

So you've got 2 something something 1.

"goes to" is written >.

So you've got 2> something 1.

2>filename means send standard error to filename. But you don't want to send it to a file called 1. You want something else: the number of a file that's already open. That's what the & is for.

So 2>&1.

You can also think of it like you were doing an assignment, where the > is like an equals and the & is like a $, compare:

f=$1
2>&1

To understand a command line with multiple redirections, the important thing to know is that the redirections are done left to right. See Order of redirections for more details about that.

Mikel
  • 57,299
  • 15
  • 134
  • 153
2

Not a mnemonic, but I read it as follows:

0 is stdin. 1 is stdout. 2 is stderr. > is into. < is out of. & is file descriptor (in some shells).

2>&1
2      >    &               1
stderr into file descriptor 1

redirect stderr into stdout

It might change if you have messed with any of the file descriptors prior to the redirection...

2>somefile 1>&2
2      >    somefile     1      >    &2
stderr into somefile and stdout into file descriptor 2

redirect stderr into somefile and stdout into somefile. 
Matt
  • 8,991
0

I remembered that it is always 2 -> 1. Stderr to stdout.

The middle part is always the hard one and I always messed it up, until I remembered that first comes the sharp character >, then the character I can't write in real life &.

So never 2&>1, always 2>&1

polym
  • 10,852
0

If you understand that FD2 is STDERR, you might think, "Oh, and capture STDERR where ever I send STDOUT (FD1)".

JRFerguson
  • 14,740
0

My coworkers and I usually say "two is greater than one", because most of us don't always remember that stderr is file descriptor 2 and stdout is 1 (especially those new to unix/linux), so the other mnemonics about redirecting stderr don't really work. Only problem is, you still have to remember where the ampersand goes!

HalosGhost
  • 4,790
Ogre Psalm33
  • 111
  • 3