What syntax will check if a variable name containing spaces is defined?

前端 未结 4 773
你的背包
你的背包 2021-01-05 11:45

Windows user defined environment variable names can contain any character except =.

Special characters can be included by escaping them. A simpler metho

4条回答
  •  有刺的猬
    2021-01-05 12:23

    I also love this sort of question! :)

    Here's another possible solution I came up with... using SET itself to test the existence, and using the ERRORLEVEL result:

    set "A B=foo"
    set A B >nul 2>nul&& echo 1. This works
    set "A B ">nul 2>nul&& echo 2. This works
    
    set "A weird & "complex" variable=foo"
    set A weird ^& "complex" variable >nul 2>nul&& echo 3. This works
    set "A weird & "complex" variable ">nul 2>nul&& echo 4. This works
    

    Note that this only works if your variables are unique in the sense that no variable name is the prefix of another one. Otherwise you risk false positives, as SET's default behavior is to show all variables that start with the parameter you pass. If this could be the case, you could filter the results with findstr:

    set "A B="
    set "A B C=foo"
    set "A B ">nul 2>nul&& echo 5. Failed (false positive)
    set "A B "|findstr /B /L /C:"A B=" >nul||echo 6. This works (no false positive)
    

    Also, the single trailing space after the variable name seems to be required. Without it, SET often mis-parses the input. Bizarrely, if you add an extra space between the "2>nul" and "&&" in case #3 it stops working (unless you remove the space before ">nul")... weird.

提交回复
热议问题