Quotes, Parens, and GOTOs in Delayed Expansion

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Sponge Belly
Posts: 223
Joined: 01 Oct 2012 13:32
Location: Ireland
Contact:

Quotes, Parens, and GOTOs in Delayed Expansion

#1 Post by Sponge Belly » 12 Dec 2012 14:50

Hello All!

I have the following block of code in my win2unix program: :D

Code: Select all

setlocal enabledelayedexpansion
if "%~1"=="" (if /i "!cmdcmdline!"=="!cmdcmdline:%~n0=!" (
endlocal & goto usage)) else (
if /i "!cmdcmdline!" neq "!cmdcmdline:%~n0=!" (
echo(specify input from EITHER pipe OR file--but not both 1>&2
endlocal & goto error))
endlocal


Delayed expansion is on, so I tried removing the quotes from the string comparisons and got a ") not expected at this time" error. :?:

My suspicion fell on the GOTOs so I reformatted the code a little and ended up with:

Code: Select all

setlocal enabledelayedexpansion
if .%~1==. (if /i !cmdcmdline!==!cmdcmdline:%~n0=! (
endlocal & goto usage)
) else (
if /i !cmdcmdline! neq !cmdcmdline:%~n0=! (
echo(specify input from EITHER pipe OR file--but not both 1>&2
endlocal & goto error)
)
endlocal


And it worked! :shock:

My question is why does removing a few unnecessary quotes from string comparisons in delayed expansion make GOTO suddenly hypersensitive to the number of parentheses enclosing it? Is there no end to Batch's eccentric behaviour?

PS: Why aren't there smilies for "shameless plug" and "total bewilderment"? I'd put both of them to good use! ;-)

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Quotes, Parens, and GOTOs in Delayed Expansion

#2 Post by Ed Dyreen » 12 Dec 2012 17:36

Sponge Belly wrote:

Code: Select all

setlocal enabledelayedexpansion
if "%~1"=="" (if /i "!cmdcmdline!"=="!cmdcmdline:%~n0=!" (
endlocal & goto usage)) else (
if /i "!cmdcmdline!" neq "!cmdcmdline:%~n0=!" (
echo(specify input from EITHER pipe OR file--but not both 1>&2
endlocal & goto error))
endlocal

Delayed expansion is on, so I tried removing the quotes from the string comparisons and got a ") not expected at this time" error. :?:
Special characters have to be either escaped or enclosed within quotes.

Code: Select all

@echo off &setlocal enabledelayedexpansion

echo.if "%~1"==""

if "%~1"=="" (

echo.if /i !cmdcmdline!_
echo.    ==!cmdcmdline^:%%~n0^=!_

   if /i !cmdcmdline!==!cmdcmdline^:%%~n0^=! (

      endlocal
      goto :usage
   )

) else (

echo.if /i !cmdcmdline!_
echo.  neq !cmdcmdline^:%%~n0^=!_

   if /i !cmdcmdline! neq !cmdcmdline^:%%~n0^=! (

      echo(specify input from EITHER pipe OR file--but not both 1>&2
      endlocal
      goto :error
   )
)

endlocal
:usage
:error
pause
exit

Code: Select all

if "/thisWorks"==""
if /i C:\WINDOWS\system32\cmd.exe  /k ""F:\...\ren.CMD" /thisWorks" _
  neq C:\WINDOWS\system32\cmd.exe  /k ""F:\...\ren.CMD" /thisWorks" _
Druk op een toets om door te gaan. . .
ed

Post Reply