在 Windows 命令行中使用批处理文件中的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14286457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using parameters in batch files at Windows command line
提问by APerson
In Windows, how do you access arguments passed when a batch file is run?
在 Windows 中,如何访问运行批处理文件时传递的参数?
For example, let's say I have a program named hello.bat
. When I enter hello -a
at a Windows command line, how do I let my program know that -a
was passed in as an argument?
例如,假设我有一个名为hello.bat
. 当我hello -a
在 Windows 命令行中输入时,如何让我的程序知道它-a
是作为参数传入的?
回答by Jon
As others have already said, parameters passed through the command line can be accessed in batch files with the notation %1
to %9
. There are also two other tokens that you can use:
正如其他人已经说过的,通过命令行传递的参数可以在批处理文件中访问,注释%1
为%9
. 您还可以使用另外两个令牌:
%0
is the executable (batch file) name as specified in the command line.%*
is all parameters specified in the command line-- this is very useful if you want to forward the parameters to another program.
%0
是命令行中指定的可执行文件(批处理文件)名称。%*
是命令行中指定的所有参数——如果您想将参数转发到另一个程序,这将非常有用。
There are also lots of important techniques to be aware of in addition to simply how to access the parameters.
除了简单的如何访问参数之外,还有许多重要的技术需要注意。
Checking if a parameter was passed
检查参数是否被传递
This is done with constructs like IF "%~1"==""
, which is true if and only if no arguments were passed at all. Note the tilde character which causes any surrounding quotes to be removed from the value of %1
; without a tilde you will get unexpected results if that value includes double quotes, including the possibility of syntax errors.
这是通过类似 的构造完成的,IF "%~1"==""
当且仅当根本没有传递参数时才为真。请注意波浪号字符,它会导致从%1
;的值中删除任何周围的引号。没有波浪号,如果该值包含双引号,您将得到意想不到的结果,包括语法错误的可能性。
Handling more than 9 arguments (or just making life easier)
处理超过 9 个参数(或只是让生活更轻松)
If you need to access more than 9 arguments you have to use the command SHIFT
. This command shifts the values of all arguments one place, so that %0
takes the value of %1
, %1
takes the value of %2
, etc. %9
takes the value of the tenth argument (if one is present), which was not available through any variable before calling SHIFT
(enter command SHIFT /?
for more options).
如果您需要访问 9 个以上的参数,则必须使用命令SHIFT
. 此命令将所有参数的值移一位,以便%0
取 的值%1
、%1
取 的值%2
等。%9
取第十个参数的值(如果存在),在调用之前无法通过任何变量获得该值SHIFT
(输入命令SHIFT /?
以获取更多选项)。
SHIFT
is also useful when you want to easily process parameters without requiring that they are presented in a specific order. For example, a script may recognize the flags -a
and -b
in any order. A good way to parse the command line in such cases is
SHIFT
当您想要轻松处理参数而不要求它们按特定顺序显示时,这也很有用。例如,一个脚本可以识别标志-a
,并-b
以任意顺序。在这种情况下解析命令行的好方法是
:parse
IF "%~1"=="" GOTO endparse
IF "%~1"=="-a" REM do something
IF "%~1"=="-b" REM do something else
SHIFT
GOTO parse
:endparse
REM ready for action!
This scheme allows you to parse pretty complex command lines without going insane.
这个方案允许你解析非常复杂的命令行而不会发疯。
Substitution of batch parameters
批量参数的替换
For parameters that represent file names the shell provides lots of functionality related to working with files that is not accessible in any other way. This functionality is accessed with constructs that begin with %~
.
对于表示文件名的参数,shell 提供了许多与处理无法以任何其他方式访问的文件相关的功能。使用以 开头的结构访问此功能%~
。
For example, to get the size of the file passed in as an argument use
例如,要获取作为参数传入的文件的大小,请使用
ECHO %~z1
To get the path of the directory where the batch file was launched from (very useful!) you can use
要获取启动批处理文件的目录的路径(非常有用!),您可以使用
ECHO %~dp0
You can view the full range of these capabilities by typing CALL /?
in the command prompt.
您可以通过CALL /?
在命令提示符中键入来查看所有这些功能。
回答by Eric Leschinski
Using parameters in batch files: %0 and %9
在批处理文件中使用参数: %0 和 %9
Batch files can refer to the words passed in as parameters with the tokens: %0
to %9
.
批处理文件可以使用标记引用作为参数传入的单词:%0
to %9
。
%0 is the program name as it was called.
%1 is the first command line parameter
%2 is the second command line parameter
and so on till %9.
parameters passed in on the commandline must be alphanumeric characters and delimited by spaces. Since %0
is the program name as it was called, in DOS %0
will be empty for AUTOEXEC.BAT if started at boot time.
在命令行中传入的参数必须是字母数字字符并以空格分隔。由于%0
是调用的程序名称,%0
如果在启动时启动,在 DOS中 AUTOEXEC.BAT 将为空。
Example:
例子:
Put the following command in a batch file called mybatch.bat
:
将以下命令放入名为 的批处理文件中mybatch.bat
:
@echo off
@echo hello %1 %2
pause
Invoking the batch file like this: mybatch john billy
would output:
像这样调用批处理文件:mybatch john billy
将输出:
hello john billy
Get more than 9 parameters for a batch file, use: %*
为一个批处理文件获取 9 个以上的参数,使用:%*
The Percent Star token %*
means "the rest of the parameters". You can use a for loop to grab them, as defined here:
Percent Star 令牌的%*
意思是“其余参数”。您可以使用 for 循环来获取它们,如下定义:
http://www.robvanderwoude.com/parameters.php
http://www.robvanderwoude.com/parameters.php
Notes about delimiters for batch parameters
关于批处理参数分隔符的注意事项
Some characters in the command line parameters are ignored by batch files, depending on the DOS version, whether they are "escaped" or not, and often depending on their location in the command line:
命令行参数中的某些字符会被批处理文件忽略,这取决于 DOS 版本,它们是否被“转义”,并且通常取决于它们在命令行中的位置:
commas (",") are replaced by spaces, unless they are part of a string in
double quotes
semicolons (";") are replaced by spaces, unless they are part of a string in
double quotes
"=" characters are sometimes replaced by spaces, not if they are part of a
string in double quotes
the first forward slash ("/") is replaced by a space only if it immediately
follows the command, without a leading space
multiple spaces are replaced by a single space, unless they are part of a
string in double quotes
tabs are replaced by a single space
leading spaces before the first command line argument are ignored
回答by rud3y
Batch Files automatically pass the text after the program so long as their are variables to assign them to. They are passed in order they are sent; e.g. %1 will be the first string sent after the program is called, etc.
批处理文件会在程序之后自动传递文本,只要它们是要分配给它们的变量即可。它们按发送顺序传递;例如 %1 将是程序被调用后发送的第一个字符串,等等。
If you have Hello.bat and the contents are:
如果你有 Hello.bat 并且内容是:
@echo off
echo.Hello, %1 thanks for running this batch file (%2)
pause
and you invoke the batch in command via
然后您通过命令调用批处理
hello.bat APerson241 %date%
你好.bat APerson241 %date%
you should receive this message back:
您应该会收到此消息:
Hello, APerson241 thanks for running this batch file (01/11/2013)
您好,APerson241 感谢您运行此批处理文件 (01/11/2013)
回答by Garret Wilson
@Jon's :parse
/:endparse
scheme is a great start, and he has my gratitude for the initial pass, but if you think that the Windows torturous batch system would let you off that easy… well, my friend, you are in for a shock. I have spent the whole day with this devilry, and after much painful research and experimentation I finally managed something viable for a real-life utility.
@Jon 的:parse
/:endparse
方案是一个很好的开始,他对最初的通过表示感谢,但是如果您认为 Windows 折磨人的批处理系统会让您那么轻松……好吧,我的朋友,您会感到震惊。我花了一整天的时间在这个恶魔身上,经过大量痛苦的研究和实验,我终于设法实现了一些对现实生活实用程序可行的东西。
Let us say that we want to implement a utility foobar
. It requires an initial command. It has an optional parameter --foo
which takes an optionalvalue (which cannot be another parameter, of course); if the value is missing it defaults to default
. It also has an optional parameter --bar
which takes a requiredvalue. Lastly it can take a flag --baz
with no value allowed. Oh, and these parameters can come in any order.
假设我们要实现一个实用程序foobar
。它需要一个初始命令。它有一个可选参数--foo
,它接受一个可选值(当然不能是另一个参数);如果缺少该值,则默认为default
. 它还有一个可选参数--bar
,它需要一个必需的值。最后,它可以带一个--baz
没有允许值的标志。哦,这些参数可以按任何顺序出现。
In other words, it looks like this:
换句话说,它看起来像这样:
foobar <command> [--foo [<fooval>]] [--bar <barval>] [--baz]
Complicated? No, that seems pretty typical of real life utilities. (git
anyone?)
复杂的?不,这似乎是现实生活中的公用事业的典型代表。(git
有人吗?)
Without further ado, here is a solution:
废话不多说,解决办法如下:
@ECHO OFF
SETLOCAL
REM FooBar parameter demo
REM By Garret Wilson
SET CMD=%~1
IF "%CMD%" == "" (
GOTO usage
)
SET FOO=
SET DEFAULT_FOO=default
SET BAR=
SET BAZ=
SHIFT
:args
SET PARAM=%~1
SET ARG=%~2
IF "%PARAM%" == "--foo" (
SHIFT
IF NOT "%ARG%" == "" (
IF NOT "%ARG:~0,2%" == "--" (
SET FOO=%ARG%
SHIFT
) ELSE (
SET FOO=%DEFAULT_FOO%
)
) ELSE (
SET FOO=%DEFAULT_FOO%
)
) ELSE IF "%PARAM%" == "--bar" (
SHIFT
IF NOT "%ARG%" == "" (
SET BAR=%ARG%
SHIFT
) ELSE (
ECHO Missing bar value. 1>&2
ECHO:
GOTO usage
)
) ELSE IF "%PARAM%" == "--baz" (
SHIFT
SET BAZ=true
) ELSE IF "%PARAM%" == "" (
GOTO endargs
) ELSE (
ECHO Unrecognized option %1. 1>&2
ECHO:
GOTO usage
)
GOTO args
:endargs
ECHO Command: %CMD%
IF NOT "%FOO%" == "" (
ECHO Foo: %FOO%
)
IF NOT "%BAR%" == "" (
ECHO Bar: %BAR%
)
IF "%BAZ%" == "true" (
ECHO Baz
)
REM TODO do something with FOO, BAR, and/or BAZ
GOTO :eof
:usage
ECHO FooBar
ECHO Usage: foobar ^<command^> [--foo [^<fooval^>]] [--bar ^<barval^>] [--baz]
EXIT /B 1
Yes, it really is that bad. See my similar post at https://stackoverflow.com/a/50653047/421049, where I provide more analysis of what is going on in the logic, and why I used certain constructs.
是的,真的很糟糕。请参阅我在https://stackoverflow.com/a/50653047/421049 上的类似帖子,在那里我提供了对逻辑中发生的事情的更多分析,以及我使用某些结构的原因。
Hideous. Most of that I had to learn today. And it hurt.
可怕。我今天必须学习其中的大部分内容。而且很痛。
回答by tohava
Use variables i.e. the .BAT
variables and called %0
to %9
使用变量,即该.BAT
变量,并呼吁%0
以%9