2011/03/14

Avoiding unwanted IO redirection after echo in command line scripting.

If you happen to work with computers and you are a programmer or other power user, you may have cause to work with command line scripts or, as they used to be called, batch files. This little tidbit applies to XP, Vista, 2k8, and probably Windows 7, and it may even apply to some of the *nix command prompt / bash / things as well. But I've never, in years and years of doing this seen it documented (as an error) or seen the workaround.


Try this command at the prompt:

echo test 2>test.txt


One might expect to see nothing on the console and then if you entered:

type test.txt

you might expect to see "test 2"


In fact, you see "test" on the console right after the echo and text.txt is empty!


What happened? The 2> is redirecting any error messages from echo test to the file test.txt. It is being interpreted as a stderr redirect and that leaves no > to send "test" into the file. Experienced programmers won't be shocked by that, although I expect you might be tripped up by it as I was. In my case, I was using a web script to build a batch file that a user could download and execute after filling out a form on the web page; it's an easy / tricky way to build a "program" on the fly which is customized by the user. Some of the user input would end up being echoed into a file on the local machine. When the users happened to enter anything ending with a number, it caused the script to fail... something I didn't see comming because I didn't realze what they would enter.


Now, how to avoid it? LOL this one is what surprised me:

(echo test 2)>test.txt


Can you believe it? That actually works! So the moral of the story is that if you are going to be echoing things to a file, you should probably enclose all of those echo commands in parenthesis as a habit.


Anyway, I was just amazed to have learned that little bit after all these years, and thought I should share it incase someone else finds it useful. Yeah... right.