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:
%var%
to!var!
telling the parser the read operation should be delayed until the execution timeecho
to get the correct value. You can do it with acall
command. It works, butcall
is slower than other options(
%~fA
is the full name of the element referenced by thefor
replaceable parameter%A
)There is a difference in how
for /f
andfor
commands in previous code workfor /f
is starting acmd
instance that will execute thecd
command to output the current directory, output that is processed by the code in thedo
clause that is invoked for each output line, with the line stored in the replaceable parameterfor
without modifiers directly retrieves a reference to the element indicated, in this case.
, the current folder. In this case%~fA
is 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.