1

This is a Windows cmd.exe question. Trying to set a variable and then using && to include another command referencing that variable in one command line does not work. The variable is not set until the next line is processed.

Steps to reproduce:

set X=1 && echo %X%
%X%

echo %X%
1

set X=2 && echo %X%
1

echo %X%
2

Is there a way to make this work as expected?

Dale Mahalko
  • 187
  • 8
  • There is no need whatsoever for the two ampersands. A case could be made for one, but I'd still say that the `echo` command should just be placed on the next line. – Compo Aug 10 '17 at 14:43
  • 1
    If "This is a Windows batch file question", why your examples are taken from the command line? The first line show a different output _in a Batch file_. You may use: `set X=1 && call echo %%X%%` See [this answer](https://stackoverflow.com/questions/9970348/how-to-realize-an-assignment-within-the-if-block/9970460#9970460) – Aacini Aug 10 '17 at 14:56

1 Answers1

1

Make the first line: setlocal enabledelayedexpansion then

set X=I_AM_ECHOED && echo !X!
echo !X!

Would print

I_AM_ECHOED
I_AM_ECHOED
Alex K.
  • 171,639
  • 30
  • 264
  • 288