Markus
Markus

Reputation: 3

Windows batch if statement influenced by statements in the if block

When I execute the following Windows batch script on Windows Server 2012:

@echo off
SET v=()
IF 1 == 2 (
  echo hi
  echo %v:~0%
  echo 1 equals 2
) ELSE (
  echo 1 does not equal 2
)


IF 1 == 2 (
  echo %v:0%
  echo 1 equals 2
) ELSE (
  echo 1 does not equal 2
)

I get the following output:

1 equals 2
1 does not equal 2
1 does not equal 2

Can anybody tell me why this happens? I don't want to go into the block starting with echo hi even if the value of v is ().

Upvotes: 0

Views: 91

Answers (1)

Compo
Compo

Reputation: 38623

I'm not quite sure what your intention is, but here's how I think your issue can be fixed.

The variable %v% is parsed before the IF command is run, and that contains a problematic closing parenthesis. What happens therefore is that the code reads, echo %v:~0% as echo ( and closes the IF with ) It then parses the next line which is echo 1 equals 2, and prints it as expected.

To prevent that, either escape that parenthesis, when you define that variable:

@echo off
SET "v=(^)"
IF 1 == 2 (
  echo hi
  echo %v:~0%
  echo 1 equals 2
) ELSE (
  echo 1 does not equal 2
)


IF 1 == 2 (
  echo %v:0%
  echo 1 equals 2
) ELSE (
  echo 1 does not equal 2
)

Or, better still enable delayed expansion, so that the variable content is not parsed before the command is run, only when it is:

@echo off
SET "v=()"
setlocal enabledelayedexpansion
IF 1 == 2 (
  echo hi
  echo !v:~0!
  echo 1 equals 2
) ELSE (
  echo 1 does not equal 2
)


IF 1 == 2 (
  echo !v:0!
  echo 1 equals 2
) ELSE (
  echo 1 does not equal 2
)

Upvotes: 1

Related Questions