3

I have the following batch script

@echo off

setlocal

set TEST_DIR="E:/img"

:: for all png files in TEST_DIR
for /r "%TEST_DIR%" %%f in (*.png) do (

    :: print file full path
    echo TESTING %%f

    :: store the path into MY_VAR
    set MY_VAR=%%f

    :: print MY_VAR (always blank!?)
    echo TESTING %MY_VAR%

)

endlocal

The printing of MY_VAR always is blank. Why is that?

If the img directory contains 2 png files: - img1.png - img2.png

then here is the output from the console:

E:\img>test.cmd
TESTING E:\img\img1.png
TESTING
TESTING E:\img\img2.png
TESTING

Thanks

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
Octo
  • 543
  • 1
  • 5
  • 16
  • 3
    Search here for **batch-file delayed expansion**. This question has been asked (and answered) many times here in various forms. – Ken White Oct 06 '16 at 22:50
  • 1
    Follow @KenWhite's advice; moreover, think about [`:: label-like comment` inside a command block enclosed in `()` parentheses](http://stackoverflow.com/a/32147995/3439404) – JosefZ Oct 06 '16 at 23:02
  • Ok. Delayed expansion is a concept I didn't know. Thanks for the info. – Octo Oct 06 '16 at 23:09
  • 2
    Comments are ***not for extended discussion***, nor are they for off-topic arguments. I just removed 22 off-topic comments on this post. Please do not add any more. – elixenide Oct 07 '16 at 01:50

1 Answers1

2

I corrected the script to use delayed expansion.

@echo off

setlocal enableDelayedExpansion

set TEST_DIR="E:/img"

:: for all png files in TEST_DIR
for /r "%TEST_DIR%" %%f in (*.png) do (

    :: print file full path
    echo TESTING %%f

    :: store the path into MY_VAR
    set MY_VAR=%%f

    :: print MY_VAR
    echo TESTING !MY_VAR!

)


endlocal

The output is now correct.

E:\img>test.cmd
TESTING E:\img\img1.png
TESTING E:\img\img1.png
TESTING E:\img\img2.png
TESTING E:\img\img2.png

Thank you.

Octo
  • 543
  • 1
  • 5
  • 16