1


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
Robdll
  • 5,865
  • 7
  • 31
  • 51
  • 1
    You use delayed expansion with `!` instead of `%` signs, `if "%STRING%"=="empty" (` becomes `if "!STRING!"=="empty" (`. Btw it's a bad idea to use labels inside blocks, this results only into errors – jeb Feb 08 '16 at 10:05
  • 1
    And you don't need it. You only need it if the value changes on one line. Things in brackets are one line. Without it variables are expanded at the time the line is read. With it (!var!) it is expanded at the time used, which is incompatible with traditional batch files. As you don't change and try and use the variable on one line - you don't need it. –  Feb 08 '16 at 10:27
  • keep giving the error also using esclamation marks instead then %. How can i avoid using the labesl? – Robdll Feb 08 '16 at 13:02
  • If you need to use a LABEL in a batch file, you either use the `GOTO` or `CALL` commands. – Squashman Feb 08 '16 at 13:38

1 Answers1

0

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.

Community
  • 1
  • 1
JosefZ
  • 28,460
  • 5
  • 44
  • 83