1

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?

2
  • 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 Commented May 3, 2019 at 7:57
  • if you don't want to enabledelayedexpansion as shown by numerous duplicate questions on SO, then you can use call echo name=%%name%% Commented May 3, 2019 at 8:24

1 Answer 1

4

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!
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.