Batch: Escaping Double Quotes inside an IF statement

Viewed 15

Was writing my first CMD script that has any logic to it and had a problem that I fixed, but don't understand why what I tried originally didn't work. Maybe someone can explain. Abstracted Code:

@echo off 
setlocal 
setlocal EnableDelayedExpansion EnableExtensions

call :function 
exit \b 0

:function 
  set "dir1=^"Dir ABC^"" 
  echo %dir1%                     :: output> "Dir ABC" 
  if 1 eql 1 ( 
    set "dir1=^"Dir ABC^""        :: output > " unexpected at this point :: terminates 
    echo !dir1! 
  )
  exit \b 0 

Tried other escapes: " "". The "" doesn't terminate or get error, but outputs: ""Dir ABC"" What worked:

:function 
  set dq=" 
  set "dir1=%dq%Dir ABC%dq%" 
  echo %dir1%                         :: output> "Dir ABC" 
  if 1 eql 1 ( 
    set "dir1=!dq!Dir ABC!dq!"
    echo !dir1!                       :: output> "Dir ABC"
  )
  exit /b 0

I've seen may other posts about escaping, but none seemed to deal with code in an IF or described my situation not working.

Why do escape characters work differently inside the If clause?? Apparently something related to delayed execution.

0 Answers
Related