How to escape variables with parentheses inside if-clause in a batch file?

前端 未结 4 2028
天涯浪人
天涯浪人 2020-12-16 10:54

Running this batch file

@echo off
set a=some value with (parentheses) inside
if 1 == 1 (
    set PATH=%a%
)

gives inside was unexpect

4条回答
  •  一整个雨季
    2020-12-16 11:30

    Brackets and variables are always a pain to mix. Use a subroutine instead.

    @Echo Off
    Set a=some value with (parentheses) inside
    If 1 == 1 Call :SetPath
    Echo %Path%
    Exit /B
    
    :SetPath
    Set "Path=%a%"
    SetX "Path" "%a%"
    Exit /B
    

    I set the variable twice, once using Set for the current shell session, and one using SetX to set it system-wide for future shell sessions. Remove either if they're unneeded.

提交回复
热议问题