You can do this without using Delayed Expansion (without "setlocal enabledelayedexpansion
"), by using a "for" (loop) with "call".
@echo off
set "var1=" & set "var2="
echo var1=[%var1%], var2=[%var2%]
:rem The one-liner:
set "var1=Demo" & for /f "usebackq delims=" %%a in (`call echo ^%var1^%`) do @set "var2=%%a"
::
echo var1=[%var1%], var2=[%var2%]
:end
The output:
var1=[], var2=[]
var1=[Demo], var2=[Demo]
You can even add a second "for" loop to do the "echo var2" in the same line:
:rem The one-liner:
set "var1=Demo" & for /f "usebackq delims=" %%a in (`call echo ^%var1^%`) do @set "var2=%%a" & for /f "usebackq delims=" %%a in (`call echo var2^=[^%var2^%]`) do @echo %%a
::
:end
The "Final" output:
var2=[Demo]
Here's the breakdown of the "for" and "call":
for /f "usebackq" %%a Operates on a command that is enclosed in `backquotes`.
Executes that command and captures the output of that
command into variable %%a.
"delims=" Disables all delimiters when parsing the command
output. Default delimiters are "space" and "tab".
Not required for this specific example.
Used when the command output might contain delimiters.
(`call echo ^%var1^%`)
(`call echo var2^=[^%var2^%]`)
Use "call" to execute the echo command within a
separate process.
"^" escapes special characters like "%" and "=" when
the command is read by "for".
do @set "var2=%%a"
do @echo %%a Sets the variable "var2" from the output of the
command in the for loop.
In this case, the for command will execute just once.
If the output of the command spanned multiple lines,
the for command would execute once for each non-empty
output line.