Mike T
Mike T

Reputation: 43642

How to set cmd variables to values with on or off?

How can a cmd variable be set to the values on or off? Here is the output of an interactive cmd.exe session:

c:\>echo %myvar%
%myvar%

c:\>set myvar=x

c:\>echo %myvar%
x

c:\>set myvar=on

c:\>echo %myvar%

c:\>set myvar=off

c:\>echo %myvar%

after this last command, the command session becomes unresponsive and I need to manually close the command window. Do these values on or off hold special powers? Also ON or OFF have similar effect, so this is case-insensitive.

The closest I can get is to use quotes:

c:\>set myvar="on"

c:\>echo %myvar%
"on"

however, this is unacceptable since the variable contains quote characters.

Upvotes: 0

Views: 86

Answers (1)

SomethingDark
SomethingDark

Reputation: 14305

on and off by themselves are valid variable values.

The issue is with the fact that echo takes the strings on and off as arguments to activate or deactivate the cmd feature of displaying a line of code before executing it.

The easiest way around this is to use echo( instead of echo.

set var=on
echo(%var%

The second easiest way around this is to have literally any additional string in the echo command. Aesthetically, I'd recommend using a backspace character (ALT+08) to delete a previous character and then write on or off.

set var=on
for /f %%a in ('"prompt;$H&for %%b in (0) do rem"') do set "BS=%%a"
echo .%BS%%var%

Upvotes: 5

Related Questions