How to make SHIFT work with %* in batch files

后端 未结 7 1866
独厮守ぢ
独厮守ぢ 2020-12-24 11:38

In my batch file on Windows XP, I want to use %* to expand to all parameters except the first.
Test file (foo.bat):



        
7条回答
  •  没有蜡笔的小新
    2020-12-24 11:59

    I had to do this recently and came up with this:

    setlocal EnableDelayedExpansion
    
    rem Number of arguments to skip
    set skip=1
    
    for %%a in (%*) do (
      if not !position! lss !skip! (
        echo Argument: '%%a'
      ) else (
        set /a "position=!position!+1"
      )
    )
    
    endlocal
    

    It uses loop to skip over N first arguments. Can be used to execute some command per argument or build new argument list:

    setlocal EnableDelayedExpansion
    
    rem Number of arguments to skip
    set skip=1
    
    for %%a in (%*) do (
      if not !position! lss !skip! (
        set args=!args! %%a
      ) else (
        set /a "position=!position!+1"
      )
    )
    
    echo %args%
    
    endlocal
    

    Please note that the code above will add leading space to the new arguments. It can be removed like this:

    • How to remove trailing and leading whitespace for user-provided input in a batch file?

提交回复
热议问题