windows batch files: setting variable in for loop

与世无争的帅哥 提交于 2019-11-27 07:36:53

Your problem is that the variable get replaced when the batch processor reads the for command, before it is executed.

Try this:

SET temp=Hello, world!
CALL yourbatchfile.bat

And you'll see Hello printed 5 times.

The solution is delayed expansion; you need to first enable it, and then use !temp! instead of %temp%:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /R %%X IN (*.txt) DO (
  set temp=%%~nX
  echo directory !temp:~0,7!
)

See here for more details.

Another solution is to move the body of the for loop to a subroutine and call it.

@echo off
FOR /R %%X IN (*.txt) DO call :body %%X
goto :eof

:body
set temp=%~n1
echo directory %temp:~0,7%
goto :eof

Why do this? One reason is that the Windows command processor is greedy about parentheses, and the results may be surprising. I usually run into this when dereferencing variables that contain C:\Program Files (x86).

If the Windows command processor was less greedy, the following code would either print One (1) Two (2) or nothing at all:

@echo off
if "%1" == "yes" (
   echo 1 (One)
   echo 2 (Two)
)

However, that's not what it does. Either it prints 1 (One 2 (Two), which missing a ), or it prints 2 (Two). The command processor interprets the ) after One as the end of the if statement's body, treats the second echo as if it's outside the if statement, and ignores the final ).

I'm not sure whether this is officially documented, but you can simulate delayed expansion using the call statement:

@echo off
FOR /R %%X IN (*.txt) DO (
  set temp=%%~nX
  call echo directory %%temp:~0,7%%
)

Doubling the percent signs defers the variable substitution to the second evaluation. However, delayed expansion is much more straightforward.

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