1

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

audi02
  • 559
  • 1
  • 4
  • 16
  • firstly, rather use backslash and not forward slash. cd /d "c:\dir1" as windows use backslash by default. I would also like you to provide me with a screenshot if possible that it does not echo the new current directory. Also, unless you want to use the actual variable `%cd%` you could just do `cd` without having to `@echo %cd%` – Gerhard Jul 07 '20 at 09:40
  • `cd` without any parameters will print the current working directory. No need to use `@echo %CD%` – phuclv Jul 07 '20 at 10:19
  • @GerhardBarnard - thanks, I added snapshots. After checking according to your comment, I found that it happens only within the IF context as shown. – audi02 Jul 07 '20 at 10:38
  • 2
    ok, that is WAY different now that you added the loop.. You need delayed expansion or just use `cd` – Gerhard Jul 07 '20 at 10:41
  • This is not 'strange behaviour' for a batch file. See [here](https://stackoverflow.com/a/30284028/12343998)》and delete your duplicate question. – T3RR0R Jul 07 '20 at 10:43

1 Answers1

2

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
)
Gerhard
  • 22,678
  • 7
  • 27
  • 43