Reputation: 735
When I try delayed expansion of an environment variable with a : clause inside a .BAT file IF statement the line fails to parse/execute. Using % signs instead of ! for the expansion works. The identical delayed expansion works in other places, eg an ECHO statement. For example:
@echo off& setlocal enabledelayedexpansion
set t=abcd
echo !t:~0,2!
if %t:~0,2% == ab echo equal
if !t:~0,2! == ab echo equal
The echo !t:~0,2! correctly produces: ab
The if %t:~0,2% == ab echo equal correctly produces: equal
The if !t:~0,2! == ab echo equal issues the error: 2! was unexpected at this time
I don't understand why I can't use a delayed expansion with a : clause inside an IF statement. Without the colon clause the delayed expansion inside the IF statement works fine.
Upvotes: 1
Views: 893
Reputation: 82247
The problem is not the delayed expansion itself, it's the comma inside.
That's because the batch parser expands the delayed expansion expression later than the percent expansion.
Therefore the IF
parser sees the !t:~0,2!
and takes the comma as a separator character.
You can simply avoid this by using quotes.
Or escaping the comma.
if "!t:~0,2!" == "ab" echo equal
if !t:~0^,2! == ab echo equal
You can read about the order of the different batch parser phases at SO:How does the Windows Command Interpreter (CMD.EXE) parse scripts?
Upvotes: 2