windows 批处理文件,vista x64,if 和括号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/430376/
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
Batch files, vista x64, if and parenthesis
提问by Daniel C. Sobral
Some batch files on Windows use an IF syntax with multiple lines, as below:
Windows 上的一些批处理文件使用多行的 IF 语法,如下所示:
if var==rule (
some comands
) else (
else commands
)
Now, Windows Vista x64 decided to put all 32 bits files under "C:\Program Files (x86)". Unfortunately, whenever you use an environment variable (such as PATH) inside a multiple line IF without quotes, the parenthesis inside the variable's value confuses IF, aborting the batch file. For example:
现在,Windows Vista x64 决定将所有 32 位文件放在“C:\Program Files (x86)”下。不幸的是,每当您在不带引号的多行 IF 中使用环境变量(例如 PATH)时,变量值内的括号会混淆 IF,从而中止批处理文件。例如:
if "%OS%"=="Windows_NT" (
@setlocal
call :set_home
set _ARGS=%*
) else (
set _SCALA_HOME=%SCALA_HOME%
rem The following line tests SCALA_HOME instead of _SCALA_HOME, because
rem the above change to _SCALA_HOME is not visible within this block.
if "%SCALA_HOME%"=="" goto error1
call :set_args
)
A batch file with this will fail even though the line where %SCALA_HOME% appears does not get executed. This is rather annoying. Is there a solution for this?
即使 %SCALA_HOME% 出现的行没有被执行,带有这个的批处理文件也会失败。这比较烦人。有解决方案吗?
回答by j_random_hacker
Change all instances of %SCALA_HOME%
to !SCALA_HOME!
, and add the following near the top of the file:
将所有实例更改%SCALA_HOME%
为!SCALA_HOME!
,并在文件顶部附近添加以下内容:
setlocal enableextensions enabledelayedexpansion
The latter turns on "delayed variable expansion", which means that variables written in the form !VAR!
are not expanded until they are used, rather than when the statement itself is parsed. (In my limited experience, and certainly in this case, this means that variable expansions are less likely to be misinterpreted as actual batch file syntax constructs.) Thanks to Patrick Cuff for pointing out this better way of doing it in a comment.
后者开启了“延迟变量扩展”,这意味着在表单!VAR!
中写入的变量在使用之前不会扩展,而不是在语句本身被解析时扩展。(以我有限的经验,当然在这种情况下,这意味着变量扩展不太可能被误解为实际的批处理文件语法构造。)感谢 Patrick Cuff 在评论中指出这种更好的方法。
P.S.: As you are discovering, the cmd.exe
batch file language is horriblybroken in many ways. If you can't use a genuine scripting language (e.g. if your task needs to be performed on other computers), I would seriously recommend knocking out a quick C/C++ "script" that does the job, and compile it to .EXE.
PS:正如您所发现的,cmd.exe
批处理文件语言在很多方面都被严重破坏了。如果您不能使用真正的脚本语言(例如,如果您的任务需要在其他计算机上执行),我强烈建议您删除一个快速完成工作的 C/C++“脚本”,并将其编译为 .EXE。