Hao Zhang
Hao Zhang

Reputation: 157

Setting variables and taking effect in one batch command line

I just found out that if you do the following:

set Variable=Test & echo %Variable%  --Outputs "%Variable%"
echo %Variable%                      --Outputs "Test"

The change won't take effect until a new line runs. I need to have it take effect immediately as I need to use it with a very long, one-lined command.

Upvotes: 1

Views: 99

Answers (1)

npocmaka
npocmaka

Reputation: 57252

You need delayed expansion or call echo:

@echo off

setlocal enableDelayedExpansion

set var=val&echo !var!

endlocal

set var=val&call echo %%var%%

If you have compositions of commands put together with & or in brackets the set command will take effect after all of them are executed.So you need or delayed expansion (which will allow you to access the variables with ! instead of %) or call

To enable the delayed expansion in command prompt you need to start like this cmd /v:on :

>cmd /v:on
>set Variable=Test & echo !Variable!  

Upvotes: 2

Related Questions