I’m getting strange behavior in variable assignment in a batch script that I’ve written. The simplest example I could concoct to re-create the problem follows. I created the file type pos.bat:
@echo on
FOR /R ".\" %%F IN (*.txt) DO (
echo Look: %%F
set file=%%~dpF%%~nF
echo %file%
)
In a directory containing two *.txt files, with one in a subdirectory:
pos/
|-pos.bat
|-file1.txt
|dir/
|-file2.txt
I get the following output:
F:\pos>pos.bat
F:\pos>FOR /R ".\" %F IN (*.txt) DO (
echo Look: %F
set file=%~dpF%~nF
echo F:\pos\dir\file2
)
F:\pos>(
echo Look: F:\pos\file1.txt
set file=F:\pos\file1
echo F:\pos\dir\file2
)
Look: F:\pos\file1.txt
F:\pos\dir\file2
F:\pos>(
echo Look: F:\pos\dir\file2.txt
set file=F:\pos\dir\file2
echo F:\pos\dir\file2
)
Look: F:\pos\dir\file2.txt
F:\pos\dir\file2
Shouldn’t the value of %file% change back to F:\pos\file1.txt on the first iteration of the loop? Also, I was surprised that the value of `%file% should persist at all between calls to the script. The first call to the script behaved as I intended:
F:\pos>FOR /R ".\" %F IN (*.txt) DO (
echo Look: %F
set file=%~dpF%~nF
echo
)
F:\pos>(
echo Look: F:\pos\file1.txt
set file=F:\pos\file1
echo
)
Look: F:\pos\file1.txt
ECHO is on.
F:\pos>(
echo Look: F:\pos\dir\file2.txt
set file=F:\pos\dir\file2
echo
)
Look: F:\pos\dir\file2.txt
ECHO is on.
But all subsequent calls give me garbage results. Any help is greatly appreciated.
You need to enable delayed expansion and then use
!for the variable within the loop.At the top of your file (typically)
Within your FOR loop
Here’s a good resource on the why’s and wherefore’s.