2

I am new to Windows 10 64-bit and start Command Prompt and type the following (set variable and echo it in same line):

H:\>set a="hello" & echo %a%
%a%

H:\>set a="hello" & echo %a%
"hello"

Why do I not see "hello" the first time I echo'ed it?

Apologies if this a basic question, I cannot seem to have found the answer online.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
Harry
  • 89
  • 1
  • 1
  • 6
  • First line doesn't clear `a` after `echo`. Try `set a="hello" & echo %a% & set "a="` to verify. – dxiv Aug 22 '16 at 18:45
  • Start Command Prompt and type these three separated lines: `set a="one" & echo %a%`, then `set a="two" & echo %a%`, then `set a="three" & echo %a%`. Then, look for the difference of "Delayed Expansion" vs. %normal% expansion... – Aacini Aug 22 '16 at 18:47
  • Related: [Example of delayed expansion in batch file](http://stackoverflow.com/q/10558316) – aschipfl Aug 22 '16 at 18:52
  • 1
    [Another one](http://stackoverflow.com/questions/25324354/windows-batch-files-what-is-variable-expansion-and-what-does-enabledelayedexpa/25328044#25328044). – Aacini Aug 22 '16 at 18:53
  • and [another](http://stackoverflow.com/a/30284028/2152082). There must be dozens. – Stephan Aug 23 '16 at 05:25
  • Thank you everyone. As I am using cmd prompt, it doesn't seem possible to use delayed expansion once the prompt has opened. I have to either relaunch it with /v flag (`cmd /v`) or simply invoke batch files that have delayed expansion enabled using `setlocal enableDelayedExpansion`. – Harry Aug 23 '16 at 12:12

1 Answers1

1

This is because the line will be evaluated before the set command, so on the first run %a% will be passed as is (a string "%a%" because a was not present).

After evaluating variables the first line will look like:

set a="hello" & echo %a%

The second line will be evaluated as:

set a="hello" & echo hello

before running any commands.

Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71