2

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?

Jeff Irwin
  • 1,041
  • 8
  • 12

1 Answers1

2

There are two issues here.

1) When you assign value to variable inside brackets you need delayed expansion

2) GOTO breaks the brackets context (including within IF) and the closing bracket becomes invalid

Here's a technique that will allow you to shift inside parenthesis.

npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • 1
    Thanks! I ended up working around this problem by getting rid of `ELSE` and adding `GOTO :endcmd` after `REM Do nothing`. – Jeff Irwin Aug 28 '15 at 19:21