Monday, January 10, 2011

A peculiar behavior of the Windows "echo" command

Here's an odd little behavior. On your Windows computer, try this:

echo bryan > c:\temp\bryan.txt

(You should probably cut-and-paste the command to get it exactly, as that turns out to be important for this example.)

Now bring up the file c:\temp\bryan.txt in your favorite editor.

Meanwhile, try this command, too:

echo bryan> c:\temp\bryan2.txt

And bring up the file c:\temp\bryan2.txt in your favorite editor.

Do you see the difference?

Yes, the two commands look very similar, and the two files they produce look very similar, but they are slightly different.

Do you see it yet? It's pretty subtle ...

OK, here's the answer: in the first case, there is a trailing space character in the resulting file, but in the second case there is not! That is, the first command results in a single-line file with a line that is six characters long: 'b', 'r', 'y', 'a', 'n', ' ', while the second command results in a single-line file with a line that is five characters long: 'b', 'r', 'y', 'a', 'n'.

You'll get similar behavior when you use the "pipe" symbol ('|') to construct a command pipeline; that is,

echo bryan | some-program-that-reads-stdin

is slightly different than

echo bryan| some-program-that-reads-stdin

because in the first case the program will read a 6-character line from stdin, while in the second case the program will read a 5-character line from stdin.

I'm sure this is probably documented somewhere, but it was a surprise to me so I thought it would be worth a short note.

No comments:

Post a Comment