开发者

How to pass multiple params in batch?

In my batch file I want to pass multip开发者_如何学运维le parameters to some other application.

Now I do it

app.exe %1 %2

and it can only pass two parameters, but I want to pass all the parameters that are passed to the batch(I would rather not write %1 %2 %3 %4 ...)

Is there any magic way to do it?


There is a magic way! I knew it, but I could not remember it.

its %*


You could use the SHIFT prompt and loop through the arguments. Here is a demonstrative example where you would replace the final ECHO prompt with a prompt to load your application.

@ECHO OFF

SET PARAMS=

:_PARAMS_LOOP

REM There is a trailing space in the next line; it is there for formatting.
SET PARAMS=%PARAMS%%1 
ECHO %1
SHIFT

IF NOT "%1"=="" GOTO _PARAMS_LOOP

ECHO %PARAMS%

PAUSE

This may be useful if you need some sort of dynamic parameter counting, or if you want to disallow a certain parameter.


Another way is to use one double quoted parameter. When calling the other application, you just use the %~N device on the command line to remove the quotes.

If some parameters you intend to pass to the application are themselves double-quoted, those quote chars must be repeated twice.

Here's an illustration script that uses the first parameter as the application's name and the second as a combined parameter list to pass to the application:

@ECHO OFF
CALL %1 %~2

Here are examples of calling the script for different cases (pass one parameter or several parameters or quoted parameters).

  1. Pass 1 parameter to the app:

    C:\>mybatch.bat app.exe "app_param"
    C:\>mybatch.bat app.exe app_param
    
  2. Pass several parameters:

    C:\>mybatch.bat app.exe "app_param1 app_param2 app_param3"
    
  3. Pass a parameter that includes spaces (and so must be quoted):

    C:\>mybatch.bat app.exe """parameter with spaces"""
    
  4. A combined example: some parameters are with spaces, others aren't:

    C:\>mybatch.bat app.exe "param_with_no_spaces ""parameter with spaces"" another_spaceless_param"
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜