Search code examples
batch-filecd

batch file %cd% doesn't changed after changing current working directory


I wrote a batch file (windows os) that prints current working directory using %CD%, but even I change the current directory , the value of %CD% doesn't changed. This strange behavior happens to me in context of "IF" statement.

Here is a snapshot of the folders and the batch file Test.bat

enter image description here

I call the batch file from dir3.

It works ok if the code is as follows :

@echo off 
@echo %CD%
cd /d c:\temp\dir1
@echo %CD%

enter image description here

but in the follow code it doesn't work as shown in the snapshot of the prompt window. Even after changing the current working directory it prints the first one - c:\temp\dir3.

@echo off 
if exist "c:\bom" (
   @echo file exist already
) else (
@echo %CD%
cd /d c:\temp\dir1
@echo %CD%
)

enter image description here


Solution

  • So you are lacking delayedexpansion here. Here are 2 ways though:

    @echo off 
    setlocal enabledelayedexpansion
    if exist "c:\bom" (
      @echo file exist already
    ) else (
      @echo !CD!
      cd /d c:\temp\dir1
      @echo !CD!
    )
    

    or just use cd without echoing the variable %cd%

    @echo off 
    if exist "c:\bom" (
      @echo file exist already
    ) else (
      cd
      cd /d c:\temp\dir1
      cd
    )