Reputation: 40613
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 setting it: yes
yes
Why is this? And is there a way to make it behave as I think it should?
Upvotes: 2
Views: 242
Reputation: 16742
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%
...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.
Consider a less kludgy language (Perl, Python, PowerShell, PHP, JScript, C#, ...)
Upvotes: 6