Parenthesis in variables inside IF blocks

后端 未结 5 1025
天命终不由人
天命终不由人 2021-02-07 12:12

In one of my scripts, I need to use variables that contain parenthesis inside IF statements, but either the string is missing a closing parenthesis or the script ex

5条回答
  •  时光说笑
    2021-02-07 12:48

    As others already pointed out, the unescaped and unquoted closing parenthesis ) unintentionally ends the parenthesised if block.

    Besides escaping, quotation, delayed expansion and "disappearing quotes", there are the following further options:

    1. Use a for meta-variable on the quoted value and remove the quotes by the ~-modifier:

       @echo off
      
       set "PATH=%ProgramFiles(x86)%"
       echo Perfect output:  %PATH%
       if not "%PATH%" == "" (
           rem Variable is defined
           for %%P in ("%PATH%") do echo Unbroken output: %%~P
       )
      
       pause > nul
      
    2. Use the call command to initiate another variable expansion phase, together with doubled (escaped) %-symbols:

       @echo off
      
       set "PATH=%ProgramFiles(x86)%"
       echo Perfect output:  %PATH%
       if not "%PATH%" == "" (
           rem Variable is defined
           call echo Unbroken output: %%PATH%%
       )
      
       pause > nul
      
    3. Do escaping by sub-string substitution, which happens before ^-escaping is detected:

       @echo off
      
       set "PATH=%ProgramFiles(x86)%"
       echo Perfect output:  %PATH%
       if not "%PATH%" == "" (
           rem Variable is defined
           echo Unbroken output: %PATH:)=^)%
       )
      
       pause > nul
      

提交回复
热议问题