Why does attempting to echo an undefined environment variable result in the message “ECHO is on”?

Raymond Chen

Raymond

From a batch file, suppose you try to echo the contents of a variable that hasn’t been defined:

set AWESOME=1
echo %AWESUM%

This prints ECHO is off. What’s up with that?

The first half of the puzzle is knowing that if a variable is not defined, then it expands to an empty string. Therefore, after expension, the command

echo %AWESUM%

becomes simply

echo

The second half of the puzzle is knowing that the ECHO command, if run with no command line, reports the current echo state, printing either ECHO is on or ECHO is off, accordingly.

Putting it all together: If you try to echo the value of an undefined variable, and the variable is not defined, then the echo command gets a blank command line, at which point it reports its current state.

So how do you echo the value of a variable that might be undefined?

One way is to put something else on the command line.

echo AWESUM=%AWESUM%

If AWESUM is not defined, this will expand to

echo AWESUM=

and that prints AWESUM=.

Okay, but what if you really want to echo the value on a line all by itself?

You can exploit a quirk of the ECHO command: If you follow the word ECHO immediately with a period (no space), then the period is not echoed, but the presence of the period suppresses the “no command line” behavior, and you get a blank line.

ECHO.

That prints a blank line.

If you want to print a variable that might not be defined, you would say

ECHO.%AWESUM%

This quirk of the ECHO command was originally a bug in the command line parser, but once people discovered it, the bug became elevated to a feature. (The phenomenon of a bug elevated to a feature happens a lot. Obligatory XKCD.)

Exercise: Explain the output of this batch file, and how would you fix it so it prints /??

set message=/?
echo %message%
Raymond Chen
Raymond Chen

Follow Raymond