Interesting question (I like these basic syntax questions).
Obviously, you know how to test it with extension delay, as well as FOR parameters.
@echo off setlocal set "AAA BBB=value" set ""AAA BBB"=" set "AAA=" for %%a in ("AAA BBB") do if defined %%~a echo FOR: This works setlocal EnableDelayedExpansion set "varname=AAA BBB" if defined !varname! echo Delayed: This works if defined %varname% ( echo percent: Never comes here ) ELSE ( echo percent: Never comes here ? ) if defined AAA^ BBB ( echo escape1: Never comes here ) ELSE ( echo escape1: fails ) set AAA=Hello if defined AAA^ BBB ( echo escape2: It only test for AAA the BBB will be "removed" ) ELSE ( echo escape2: fails ) set "space= " if defined AAA!space!BBB echo inject space: This works if defined "AAA BBB" (echo Quote1: Never comes here ) ELSE ( echo Quote1: Fails ) set ""AAA BBB"=value" if defined "AAA BBB" echo Quote2: This works, it checks for "AAA BBB" with quotes
In my example, in the escape2 example, the parser first split the string into tokens as follows:
<if> <defined> <AAA BBB> <echo .... But at run time if, if it is defined, it re-looks at the <AAA BBB> token, so it only gets AAA .
You cannot enter a second escape, for example AAA^^^ BBB , since it only searches for a variable named AAA^
I don't see a solution without the / FOR delay, since escaping space always fails.
EDIT: it can also be solved with SET <varname>
The ijprest solution uses the SET command to test a variable without the need to escape the var name.
But it also shows interessting behavior with spaces inside and at the end of varname.
These rules seem to follow:
SET varname searches for all variables starting with varname, but first removes all characters after the last space character varname and removes all leading spaces. Thus, you cannot search for variables beginning with a space (but it is also difficult to create such a varname).
The same behavior is also active if the variable name is enclosed in quotation marks, but then another rule exists.
First delete all characters after the last quote if there are at least two quotation marks. Use the text inside quotation marks and use the "space" -rule.
Example.
set " abc def ghi" junk junk *** 1. removes the junk set " abc def ghi" *** 2. removes the quotes set abc def ghi *** 3. removes all after the last space, and the trailing spaces set abc def *** Search all variables beginning with abc def