Friday, January 23, 2009

Numbered Output Redirection

Today my boss pointed out something to me which is kind of shocking even though you already know how stupid the command processor is.  Now we all know 2> is for redirecting stderr.  Simply > or 1> is stdout.  For stdin you use < or (less widely known) 0<.

But what if you do 3> or 4> or 5<?  Surely it does not interpret that as some special file handle?  Well, if you thought that, you’d be wrong.  Just like I was.  Try this:

echo Hi 3> out.txt

You’d expect to see Hi 3, wouldn’t you?  But nooooo, you’ll see Hi instead.

Where does the 3 go?  Well, the good interpreter thinks it’s a special file handle.  Crazy isn’t it?  But what if you really want to print Hi 3?  What do you do?  Thankfully the solution is easy and pretty obvious.

echo Hi 3 > out.txt

Yup, just put a space between 3 and >, and you’re good to go.

2 comments:

Anders said...

or you flip it around and go: >out.txt echo Hi 3

Bucket of Money said...

What a great blog for us batch nerds. Thanks very much.