does the variable 'var' gets destroyed before displaying its value?
@echo off
FOR /f "tokens=* delims=" %%G IN ('dir') DO (
set var=%%G
echo %var%
)
does the variable 'var' gets destroyed before displaying its value?
@echo off
FOR /f "tokens=* delims=" %%G IN ('dir') DO (
set var=%%G
echo %var%
)
This will never work since the reference to %var%
is resolved when the body of the loop is parsed. You have to enable delayed variable expansion and use !var!
instead:
@ECHO OFF
SETLOCAL EnableDelayedExpansion
FOR /F "tokens=* delims= " %%G IN ('dir') DO (
SET VAR=%%G
ECHO !VAR!
)
ENDLOCAL
You can read all about it by type SET /?
at a command line ;-)
You need delayed expansion:
@setlocal enableextensions enabledelayedexpansion
@echo off
FOR /f "tokens=* delims=" %%G IN ('dir') DO (
set var=%%G
echo !var!
)
endlocal
The reason it doesn't appear to be working is because %var%
is evaluated at the time the entire command is parsed. The command is the entire four lines of the for
statement. By using delayed expansion, you defer the evaluation of !var!
to when the actual echo
is executed, when it's been set correctly.