How do i handle Delayed Expansion in a batch -



i'm having trouble understanding how call batch function without having problem delayedexpansion error

) unexpected @ time.

after few searches understood it's because of enabled delayed expansion, don't how 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 

never use :label nor :: label-like comment inside command block enclosed in () parentheses. check this stackoverflow thread proof.

@echo off setlocal enableextensions rem in current code snippet: no need 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 return here     )     rem conjoint `dontdo` , `dosomething` continues here ) goto:eof  :dosomething     echo doingsomething goto:eof 

note

  • double quotes in set, e.g. set "string=%~2"
  • parameter extensions in %~1 , %~2
  • double quotes in if "%run_mode%"=="1" (; without them, if %run_mode%==1 ( result 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 off message in case of empty variable string, i.e. true condition result in if "%string%"=="" statement

read http://ss64.com/nt/call.html , http://ss64.com/nt/goto.html well.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -