0

I've got the code below, try to re-set variable "name" inside an if-else block:

@echo off
set name=kk
echo %name%
if "%name%"=="jj" (
echo case1
) else (
echo case2
set name=ll
echo name=%name%
)

Under cmd of win10, it outputs:

aa
kk
case2
name=kk

This is weird, I wish that my last echo should print:

name=ll

Seems the "set name=ll" didn't work. So would you help to explain why it didn't work as I expected, and how to fix it?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • 1
    Your `set` commands are working fine, the issue you're experiencing is with your use of `%name%`. Possible duplicate of [Variables are not behaving as expected](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected) – Compo May 03 '19 at 07:57
  • if you don't want to `enabledelayedexpansion` as shown by numerous duplicate questions on SO, then you can use `call echo name=%%name%%` – Gerhard May 03 '19 at 08:24

1 Answers1

3

You need a delayed expansion

@echo off
setlocal enableDelayedExpansion
set name=kk
echo %name%
if "%name%"=="jj" (
  echo case1
) else (
  echo case2
  set name=ll
  echo name=!name!
)
npocmaka
  • 55,367
  • 18
  • 148
  • 187