【问题标题】:Variable expression %Var% not working in for loop in batch file变量表达式 %Var% 在批处理文件中的 for 循环中不起作用
【发布时间】:2018-07-03 15:53:20
【问题描述】:
FOR /F "tokens=* USEBACKQ" %F IN (java -jar %MAVEN_HOME%\jenkins-cli.jar -s http://someip.com build /dev/ -s  --username **** --password ***) DO (SET var=%F)

这里的%MAVEN_HOME% 值没有被实际值替换,但是当我在没有for 循环的情况下运行它时,它工作正常。

有人可以解决这个问题并将MAVEN_HOME 替换为实际值吗?

【问题讨论】:

  • 如果这是在 .bat 文件脚本中,您必须在 F 变量上加倍 % 字符。使用%%F。此外,将 java 命令放在撇号中。如果要将命令放在反引号中(GRAVE ACCENT),则必须指定"usebackq tokens=*"

标签: batch-file for-loop cmd variable-expansion


【解决方案1】:

您需要像这样将命令放在` `

FOR /F "tokens=* USEBACKQ" %F IN (`java -jar %MAVEN_HOME%\jenkins-cli.jar -s http://someip.com build /dev/ -s  --username **** --password ***`) DO (SET var=%F)

因为语法是

C:\>for /?
Runs a specified command for each file in a set of files.

FOR %variable IN (set) DO command [command-parameters]

  %variable  Specifies a single letter replaceable parameter.
  (set)      Specifies a set of one or more files.  Wildcards may be used.
  command    Specifies the command to carry out for each file.
  command-parameters
             Specifies parameters or switches for the specified command.

To use the FOR command in a batch program, specify %%variable instead
of %variable.  Variable names are case sensitive, so %i is different
from %I.

...

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]

    or, if usebackq option present:

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]

如您所见,您有USEBACKQ,因此该命令必须用反引号括起来,并且它还表示如果您想在批处理文件中使用for 命令,则必须将百分比加倍

【讨论】:

  • 嘿@phuclv,这样也帮不了我。问题是使用引号后这个命令行为不端..即使它从命令中删除了几个单词。请尝试执行这个命令
  • @arjun,如果您从批处理文件运行命令,您应该这样做,因为您已经为它添加了标签,您还需要加倍元变量的百分比字符,%F 变为 %%F
  • @arjunkumarmehta 如果您运行for /?,您会看到“要在批处理程序中使用 FOR 命令,请指定 %%variable 而不是 %variable
  • 嘿,谢谢大家,终于成功了。包括 ' ' 是正确的答案。
猜你喜欢
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多