lundi 7 mai 2018

How to deal with nested if blocks in BATCH scripts?

I have an issue with my batch script likely related to the nested blocks syntax.

I have two scripts: a main script, and a start script in order to start the main one. Both are respectively named "script.bat" and "start.bat" for the example.

Below the scripts (MCVE):

script.bat

@echo off
set init="%1"
set bool=%2
set switch=%3
if %bool%==true (
    set var=%init:"=%
    set check=false
    if "%switch%"=="I" (
        if "%var%"=="A" set check=true
        if "%var%"=="B" set check=true
        if "%var%"=="C" set check=true
        if "%var%"=="D" set check=true
        if "%var%"=="E" set check=true
        if "%var%"=="F" set check=true
        if "%var%"=="G" set check=true
    )
    if "%switch%"=="II" (
        if "%var%"=="A" set check=true
        if "%var%"=="B" set check=true
        if "%var%"=="C" set check=true
        if "%var%"=="D" set check=true
        if "%var%"=="E" set check=true
    )
    if "%switch%"=="III" (
        if "%var%"=="A" set check=true
        if "%var%"=="B" set check=true
        if "%var%"=="C" set check=true
        if "%var%"=="D" set check=true
        if "%var%"=="E" set check=true
        if "%var%"=="F" set check=true
    )
    if %check%==false set code=1
    if %check%==true set code=0
    if %check%==true set result=%var%
)
if %bool%==false echo Skipped!
if %bool%==false goto quit
if defined result (
    echo RESULT = %result% [exit code: %code%]
) else (
    echo RESULT = NULL [exit code: %code%]
)
:quit
echo.
pause
exit

start.bat

@echo off
start script.bat C true II
start script.bat F true II
start script.bat B false I

Here is the expected results (It should prompt three Windows consoles as below.)

First console:

RESULT = C [exit code: 0]

Press any key to continue...

Second console:

RESULT = NULL [exit code: 1]

Press any key to continue...

Third console:

Skipped!

Press any key to continue...

Instead of that, I have the error below in each of the three consoles:

set was unexpected at this time.

Thanks for your help and sorry if my english is inaccurate sometimes.

Have a nice day. :)

Aucun commentaire:

Enregistrer un commentaire