Windows 用户定义的环境变量名称可以包含除 =
之外的任何字符。
可以通过转义来包含特殊字符。一种更简单的方法是简单地将整个 SET 表达式括在引号中。例如:
set "A weird & "complex" variable=My value"
set A weird ^& "complex" variable=My value
上面的两个表达式给出了相同的结果。变量名是 A weird & "complex"variable
值是 My value
IF DEFINED 结构用于测试变量是否已定义。引号不适用于此测试,必须转义名称中的特殊字符(包括引号)。
set "A&B=value"
if defined A^&B echo This works
if defined "A&B" echo This does not work
上面的转义测试工作得很好。引用的测试不起作用
但是如何测试包含空格的变量是否存在?
set "A B=value"
if defined A^ B echo this does not work!
看起来上面的方法应该有效,但实际上没有!
我正在寻找一个不涉及使用 %A B% 或 !A B! 扩展变量的答案
最佳答案
有趣的问题(我喜欢这个语法基础问题)。
显然,您知道如何使用延迟扩展来检查它,并且 FOR 参数也有效。
@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
在我看来,在 escape2 示例中,解析器首先以这种方式将行拆分为标记:
<if> <defined> <AAA BBB> <echo ....
但在 if defined 执行时,它会重新扫描 <AAA BBB>
token 所以它只得到 AAA
.
你不能像 AAA^^^ BBB
一样注入(inject)第二个转义符因为这只搜索名为 AAA^
的变量
我看不到不延迟/FOR 的解决方案,因为空间转义总是失败。
编辑:也可以用 SET <varname>
解决强>
ijprest 的解决方案是使用 SET 命令来测试变量,而不需要对 varname 进行转义。
但它也显示了 varname 内部和末尾带有空格的有趣行为。
它似乎遵循这些规则:
SET varname
搜索以 varname 开头的所有变量,但首先它会删除 varname 的最后一个空格字符之后的所有字符,然后删除所有前导空格。
所以你不能搜索以空格开头的变量(但创建这样的变量名也有点棘手)。
如果变量名被引号括起来,同样的行为也有效,但随后又存在一个规则。
如果至少有两个引号,则首先删除最后一个引号之后的所有字符。
使用引号内的文本,并使用“空格”规则。
示例。
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
关于windows - 什么语法将检查是否定义了包含空格的变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8254571/