1

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.

Compo
  • 36,585
  • 5
  • 27
  • 39
Paul Houle
  • 735
  • 9
  • 17

1 Answers1

2

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?

Community
  • 1
  • 1
jeb
  • 78,592
  • 17
  • 171
  • 225
  • Appreciate it -- that solved my problem since I was working with strings in that case. Still can be trouble with numeric IF comparisons, eg set n=123& if !n:~1,2! gtr 5 -- can't enclose the args in quotes because that forces a string comparison. Using a set beforehand and removing the delayed expansion from the if statement fixes that. – Paul Houle May 02 '17 at 23:54
  • 1
    @PaulH You can also escape the comma with a caret – jeb May 03 '17 at 01:32