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 wrongif ==1 (in case of empty variablerun_mode, i.e. true condition result inif "%run_mode"==""statement - opening parenthesis in
echo(%string%; without it,echo %string%command shows current echo settingecho offmessage in case of empty variablestring, i.e. true condition result inif "%string%"==""statement
read http://ss64.com/nt/call.html , http://ss64.com/nt/goto.html well.
Comments
Post a Comment