批处理文件不设置变量
我想编写一个批处理文件,将简化WebService的存根的生成。问题是,在 SET
命令之一的变量没有设定值。我已经试过各种事情得到它履行这一 SET
,但无济于事。显然,缺少明显的东西。脚本的其余部分工作正常。
I'm trying to write a batch file that will simplify the generation of WebService stubs. The problem is that one of the SET
commands for a variable is not setting the value. I've tried various things to get it to honour this SET
but to no avail. Clearly missing something obvious. The rest of the script is working fine.
IF %1==-b (
ECHO %2
SET BINDINGS_FILE=%2
SHIFT & SHIFT
ECHO File: %BINDINGS_FILE%
IF EXIST "%BINDINGS_FILE%" (
SET BINDINGS=-b %BINDINGS_FILE%
) ELSE (
ECHO Please enter a valid Bindings file name: %BINDINGS_FILE%.
GOTO DONE
)
ECHO BINDINGS = %BINDINGS%
)
当我用下面的命令执行它,它打印的绑定文件作为%2
但进入它得到设置变量
是空的。
When I execute it with the following command, it prints the bindings file as %2
but the variable into which it gets SET
remains empty.
generate-stubs.bat -b wsdl/Binding.xml -p com.acme.service wsdl/WebService.wsdl
wsdl/Binding.xml
File:
Please enter a valid Bindings file name: .
Done!
任何建议AP preciated。
Any suggestions appreciated.
批处理文件的变量设置为指定的值。但你没有看到它。
Batch file is setting the variable to the indicated value. BUT you are not seeing it.
在批处理文件行分析,然后执行。由块行或块行(括号内行)。当解析器达到一行或多行的块,在变量在哪里readed所有点的参考变量被删除,与之前的变量的值替换开始执行该块。所以,如果一个变量改变其一个块中值,这个新值将不会从同一块内入店。什么正在执行不包括参照可变的,但在当code的解析的变量的值。
In batch files lines are parsed, and then executed. Line by line or block by block (lines enclosed in parenthesis). When the parser reaches a line or a block of lines, at all points where a variable is readed, the reference to the variable is removed and replaced with the value in the variable before starting to execute the block. So, if a variable changes its value inside a block, this new value will not be accesible from inside this same block. What is being executed does not include a reference to the variable but the value in the variable when the code was parsed.
要改变这种行为,可以从改变了价值相同的块中读出的变量的改变值,需要延迟扩展。
To change this behaviour, and be able to read the changed value of the variable from inside the same block that changed the value, delayed expansion is needed.
当启用延迟扩展,语法访问/读取变量可以改变(如需要)从%VAR%
到!变种!
。这指示解析器不要做初始置换和延缓访问值,直到命令的执行。
When delayed expansion is enabled, the syntax to access/read a variable can be changed (where needed) from %var%
to !var!
. This instructs the parser not to do the initial replacement and delay the access to the value until execution of the command.
所以,你的code能像
So, your code can be something like
setlocal enabledelayedexpansion
IF "%1"=="-b" (
ECHO %2
SET "BINDINGS_FILE=%~2"
SHIFT & SHIFT
ECHO File: !BINDINGS_FILE!
IF EXIST "!BINDINGS_FILE!" (
SET "BINDINGS=-b !BINDINGS_FILE!"
) ELSE (
ECHO Please enter a valid Bindings file name: !BINDINGS_FILE!.
GOTO DONE
)
ECHO BINDINGS = !BINDINGS!
)