Koop4 February 2016

How do i handle Delayed Expansion in a batch


I'm having some trouble understanding how to call a batch function without having problem with delayedExpansion the error i get is

) was unexpected at this time.

after few searches i understood it's because of the enabled delayed expansion, but i don't get how to handle it.

@echo off
Setlocal EnableDelayedExpansion

set RUN_MODE=%1
set STRING=%2

if %RUN_MODE%==1 (
    echo %STRING%
    if "%STRING%"=="empty" (
        :dontDo
    )
    :doSomething
    :dontDo
)
goto:eof

:doSomething
    echo doingSomething
goto:eof

Answers


JosefZ February 2016

Never use :label nor :: label-like comment inside a command block enclosed in () parentheses. Check this stackoverflow thread for proof.

@echo off
Setlocal EnableExtensions
rem in current code snippet: no need for EnableDelayedExpansion 

set "RUN_MODE=%~1"
set "STRING=%~2"

if "%RUN_MODE%"=="1" (
    echo(%STRING%
    if "%STRING%"=="empty" (
        rem dontDo
    ) else
        CALL :doSomething
        rem or `GOTO :doSomething` instead of `CALL` if don't need to return here
    )
    rem conjoint for `dontDo` and `doSomething` continues here
)
goto:eof

:doSomething
    echo doingSomething
goto:eof

Note

  • double quotes in set, e.g. set "STRING=%~2"
  • parameter extensions in %~1 and %~2
  • double quotes in if "%RUN_MODE%"=="1" (; without them, if %RUN_MODE%==1 ( could result to syntactically wrong if ==1 ( in case of empty variable RUN_MODE, i.e. true condition result in if "%RUN_MODE"=="" statement
  • opening parenthesis in echo(%STRING%; without it, echo %STRING% command shows current echo setting ECHO is off message in case of empty variable STRING, i.e. true condition result in if "%STRING%"=="" statement

Read http://ss64.com/nt/call.html and http://ss64.com/nt/goto.html as well.

Post Status

Asked in February 2016
Viewed 1,630 times
Voted 9
Answered 1 times

Search




Leave an answer