Batch file for loop through switch-like arguments?

前端 未结 2 1557
谎友^
谎友^ 2021-02-14 08:47

I\'m trying to loop through the arguments that I am passing to a batch file. Based on the argument, I want to set a variable flag true or false for use later in the script

2条回答
  •  滥情空心
    2021-02-14 09:49

    You could loop over the arguments using SHIFT, GOTO and an extra IF to check if there are no more parameters to parse:

    :loop
    IF "%~1"=="" GOTO cont
    IF /I "%~1"=="/u" SET UPDATE=Y
    IF /I "%~1"=="/p" SET PRIMARY=Y
    IF /I "%~1"=="/s" SET SECONDARY=Y
    SHIFT & GOTO loop
    
    :cont
    ...
    

    UPDATE (addressing the case when a parameter has an argument of its own)

    The SHIFT in the IF statement that checks for /d does work. The issue is that the entire line is evaluated at once and both instances of %~1 get replaced with the same value, which is /d at that point.

    So, basically the solution in this case would be to cause the interpreter to evaluate the SET DISTRO="%~1" part separately from the IF /I "%~1"=="/d". There can be various approaches to this. For instance, you could simply move SHIFT & SET DISTRO="%~1" to the next line and skip it if %~1 is not /d:

    ...
    IF /I NOT "%~1"=="/d" GOTO skip_d
    SHIFT & SET "DISTRO=%~1"
    :skip_d
    ...
    

    Another method could be to assign a special value (e.g. a ?) to DISTRO and shift when /d is encountered. Then, on the next line, check if DISTRO has that special value and set it to %~1:

    ...
    IF /I "%~1"=="/d" SHIFT & SET DISTRO=?
    IF "%DISTRO%"=="?" SET "DISTRO=%~1"
    ...
    

提交回复
热议问题