How to make SHIFT work with %* in batch files

后端 未结 7 1802
独厮守ぢ
独厮守ぢ 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 12:05

    That´s easy:

    setlocal ENABLEDELAYEDEXPANSION
      set "_args=%*"
      set "_args=!_args:*%1 =!"
    
      echo/%_args%
    endlocal
    

    Same thing with comments:

    :: Enable use of ! operator for variables (! works as % after % has been processed)
    setlocal ENABLEDELAYEDEXPANSION
      set "_args=%*"
      :: Remove %1 from %*
      set "_args=!_args:*%1 =!"
      :: The %_args% must be used here, before 'endlocal', as it is a local variable
      echo/%_args%
    endlocal
    

    Example:

    lets say %* is "1 2 3 4":
    
    setlocal ENABLEDELAYEDEXPANSION
      set "_args=%*"             --> _args=1 2 3 4
      set "_args=!_args:*%1 =!"  --> _args=2 3 4
    
      echo/%_args%
    endlocal
    

    Remarks:

    • Does not work if any argument contains the ! or & char
    • Any extra spaces in between arguments will NOT be removed
    • %_args% must be used before endlocal, because it is a local variable
    • If no arguments entered, %_args% returns * =
    • Does not shift if only 1 argument entered

提交回复
热议问题