使用感叹号的 Windows 批处理文件语法

Ayu*_*man 7 windows batch-file

在检查 Axis2 二进制发行版中的 axis2server.bat 文件的详细信息时,我看到其中一行包含类似以下内容的文本:

FOR %%c in ("%AXIS2_HOME%\lib\*.jar") DO set AXIS2_CLASS_PATH=!AXIS2_CLASS_PATH!;%%c
Run Code Online (Sandbox Code Playgroud)

下面有两个感叹号的部分是什么意思?

!AXIS2_CLASS_PATH!
Run Code Online (Sandbox Code Playgroud)

% 中的名称表示变量,不确定是什么!在批处理文件中标记平均值。

fox*_*ive 9

当您enable delayed expansionchangeset循环中的变量时,!variable!语法允许您在循环中使用该变量。

缺点是!会成为延迟扩展的毒药。

  • 这回答了这个问题,但是你能详细说明一下吗?也许一个简单的例子? (3认同)

小智 7

正如 Foxidrive 提到的,这与delayed expansion. 您可以通过help set在cmd提示符下运行来找到更多信息,其中有以下说明:

Finally, support for delayed environment variable expansion has been
added.  This support is always disabled by default, but may be
enabled/disabled via the /V command line switch to CMD.EXE.  See CMD /?

Delayed environment variable expansion is useful for getting around
the limitations of the current expansion which happens when a line
of text is read, not when it is executed.  The following example
demonstrates the problem with immediate variable expansion:

    set VAR=before
    if "%VAR%" == "before" (
        set VAR=after
        if "%VAR%" == "after" @echo If you see this, it worked
    )

would never display the message, since the %VAR% in BOTH IF statements
is substituted when the first IF statement is read, since it logically
includes the body of the IF, which is a compound statement.  So the
IF inside the compound statement is really comparing "before" with
"after" which will never be equal.  Similarly, the following example
will not work as expected:

    set LIST=
    for %i in (*) do set LIST=%LIST% %i
    echo %LIST%

in that it will NOT build up a list of files in the current directory,
but instead will just set the LIST variable to the last file found.
Again, this is because the %LIST% is expanded just once when the
FOR statement is read, and at that time the LIST variable is empty.
So the actual FOR loop we are executing is:

    for %i in (*) do set LIST= %i

which just keeps setting LIST to the last file found.

Delayed environment variable expansion allows you to use a different
character (the exclamation mark) to expand environment variables at
execution time.  If delayed variable expansion is enabled, the above
examples could be written as follows to work as intended:

    set VAR=before
    if "%VAR%" == "before" (
        set VAR=after
        if "!VAR!" == "after" @echo If you see this, it worked
    )

    set LIST=
    for %i in (*) do set LIST=!LIST! %i
    echo %LIST%
Run Code Online (Sandbox Code Playgroud)