vendredi 28 août 2015

Why do command line arguments behave strangely inside an ELSE?

I have a Windows batch-file named arg_parse.cmd that parses command line arguments under certain conditions. Under other conditions, it does something else. A minimal (not) working example is below:

@ECHO OFF

IF 0 == 1 (
    REM Do nothing
) ELSE (
    :parse
        REM Print input argument.
        ECHO.
        ECHO 1 = %1

        REM Set argument to local variable.
        SET arg1=%1

        REM Break after parsing all arguments.
        IF "%~1" == "" GOTO :endcmd

        REM Print local variable.
        ECHO arg1 = %arg1%

        SHIFT
        GOTO :parse
    :endcmd
    REM Do not remove this comment.
)

On the first iteration though the parse "loop", there is clearly an argument, however the SET appears to do nothing, as arg1 is an empty string. On further iterations, it behaves normally. For example, if I run the script with a few arguments:

arg_parse.cmd test some arguments

I get this output:

1 = test
arg1 =

1 = some
arg1 = some

1 = arguments
arg1 = arguments

1 =

Why does it behave like this on the first iteration? Further, why do I get a ) was unexpected at this time error if I remove the final comment?

Aucun commentaire:

Enregistrer un commentaire