I need to write a command which will change the current directory and print the NEW directory wrapped in some tags. I thought cd SOMEPATH & echo wkd%cd%wkd would do it but there is a problem.
Here is some example input and output
C:\Users> cd .. & echo wkd%cd%wkd
wkdC:\Userswkd
As you can see, the OLD directory was printed. Why does this happen? I also tried using newlines (since I feed the command though an external program) but that gives problems when starting command line software.
I really hope there is a solution for this.
In batch files, lines or blocks of code (code enclosed in parenthesis) are first parsed, then executed and the process repeated on the next line/block. During the parse phase all read operations to obtain a value from a variable are removed from the code, replaced with the value in the variable before starting to execute the code.
In your case, when the line is parsed
%cd%is replaced with its value before starting to execute the line and change the folder.Alternatives:
cd .. echo wkd%cd%wkd%var%to!var!telling the parser the read operation should be delayed until the execution timerem inside a batch file setlocal enabledelayedexpansion cd .. & echo wkd!cd!wkd rem from a command line cmd /v:on /q /c "cd .. & echo wkd!cd!wkd"echoto get the correct value. You can do it with acallcommand. It works, butcallis slower than other optionsrem inside a batch file cd .. & call echo wkd%%cd%%wkd rem from command line cd .. & call echo wkd^%cd^%wkdrem from command line cd .. & for %A in (.) do echo wkd%~fAwkd cd .. & for /f %A in ('cd') do echo wkd%Awkd rem in batch files the percent sign needs to be escaped cd .. & for %%A in (.) do echo wkd%%~fAwkd cd .. & for /f %%A in ('cd') do echo wkd%%Awkd(
%~fAis the full name of the element referenced by theforreplaceable parameter%A)There is a difference in how
for /fandforcommands in previous code workfor /fis starting acmdinstance that will execute thecdcommand to output the current directory, output that is processed by the code in thedoclause that is invoked for each output line, with the line stored in the replaceable parameterforwithout modifiers directly retrieves a reference to the element indicated, in this case., the current folder. In this case%~fAis used to obtain a real full name from the relative.reference into an absolute pathAll this options are only doing one thing: delay the retrieval of the current folder until the
cd ..has been executed.