I have a xyz.bat file with this content:
@set val=one
@if "%val%" equ "one" (
@set val=yes
echo val after setting it: %val%
) else (
@set val=no
)
@echo %val%
Running it in cmd.exe prints
val after setting it: one
yes
but I expected
val after开发者_JAVA百科 setting it: yes
yes
Why is this? And is there a way to make it behave as I think it should?
Everything between ( and ) is parsed as a single line (joining commands with &) – and the shell expands %var% variables at parse time
The output of set /? explains this further.
In recent versions:
@echo off
setlocal enabledelayedexpansion
set var=one
if a equ a (
set var=two
echo immediate expansion: %var%
echo delayed expansion: !var!
)
echo after: %var%
- The Old New Thing: Environment variable expansion occurs when the command is read
...but that way lies madness. For example, if you want to echo a ! in delayed expansion mode, you have to escape it twice:
echo hi^^!
(This gets parsed twice, reduced to echo hi^! the first time.) And don't even get me started on using ^ inside variables.
- The Old New Thing: What this batch file needs is more escape characters
Consider a less kludgy language (Perl, Python, PowerShell, PHP, JScript, C#, ...)
加载中,请稍侯......
精彩评论