1

I am trying to create a very simple batch script in which for every file copied to a staging directory, the script changes its working dir to that staging directory to do some work:

pushd C:\Shared\
for /r %%f in (*.dll) do (
    copy %%f C:\staging\.
    pushd C:\staging\.
      echo CWD is  %cd%
      REM do some work here
    popd
)
popd

However, to my surprise, only the first pushd gets done.

Is this a known limitation of DOS/Windows batch? If so, is there a quick workaround for this?

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
datps
  • 768
  • 1
  • 6
  • 16

1 Answers1

2

it works. Prove with the command cd:

pushd C:\Shared\
for /r %%f in (*.dll) do (
    pushd C:\staging\.
      echo CWD is  %cd%
      cd
    popd
)
popd

But because you use a variable (%cd%), that is changed and used within the same block, you need delayed Expansion:

setlocal enabledelayedexpansion
pushd C:\Shared\
for /r %%f in (*.dll) do (
    pushd C:\staging\.
      echo CWD is  %cd%
      echo correct CWD is !cd!
      cd
    popd
)
popd
Community
  • 1
  • 1
Stephan
  • 53,940
  • 10
  • 58
  • 91
  • 1
    Thank you! I would just add that in your 2nd code snippet a `setlocal enabledelayedexpansion` is needed (I put it just before the 2nd `pushd` but that reaches maximum recursion level for setlocal, so I put it above all code). – datps Jan 12 '16 at 11:22
  • yes, normally, `setlocal ...` is the second line of a batchfile (first one would be `@echo off`). Sorry, I am so used to this, that I forgot to mention. If you want the `setlocal ...` _inside_ the `for` loop, (it's normally not neccessary) you should `endlocal` before the loop ends (`)`). – Stephan Jan 12 '16 at 12:54