Local variable in FOR DO Statement

微笑、不失礼 提交于 2020-01-06 04:51:25

问题


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%
)

回答1:


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 ;-)




回答2:


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.



来源:https://stackoverflow.com/questions/3084846/local-variable-in-for-do-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!