1

It is ok to do this in the command line:

C:\Users\ken.chen>echo|set /p=cd %cd%|clip

C:\Users\ken.chen>cd C:\Users\ken.chen

C:\Users\ken.chen\nuts\notes>echo|set /p=cd %cd%|clip

C:\Users\ken.chen\nuts\notes>cd C:\Users\ken.chen\nuts\notes

but the variabe %cd% is always my home directory if I add a doskey cc to my initialization batch file:

doskey cc=echo^|set /p=cd %cd%^|clip


C:\Users\ken.chen\nuts\notes>cc

C:\Users\ken.chen\nuts\notes>cd C:\Users\ken.chen

how to fix it? or do I need to write it in a separate batch file?

thinker3
  • 12,771
  • 5
  • 30
  • 36

2 Answers2

1

The cd variable always "contains" the same directory because it was evaluated once, when the macro was created, and at that point the home directory was current.

If you escape the % characters, however, the variable will be evaluated at every invocation of cc:

doskey cc=echo^|set /p=cd ^%cd^%^|clip

But that method of escaping the % would work only in the command line. To escape them in a batch file, use a different method:

doskey cc=echo^|set /p=cd %%cd%%^|clip
Andriy M
  • 76,112
  • 17
  • 94
  • 154
  • your answer gave me a hint, but to escape the %, i tested that ^ not works in my cmd.exe initialization .bat file, % do works. – thinker3 Aug 06 '14 at 22:57
  • You are right, I indeed tested this directly in the command line rather than in a batch file (missed the relevant detail in your question). I actually tried `%%` at first but it didn't work properly (in the command line). Well, the variable did evaluate at every invocation of `cc` but there were also `%`s around the path. I realise that this is not an issue when you use escape the percents with `%%` in a batch file, well done figuring that out! – Andriy M Aug 07 '14 at 06:02
  • @metaphy: Thank you for accepting my answer. I've updated it to match your question more accurately. – Andriy M Aug 07 '14 at 07:14
0

Can you not simply use the below?

echo.cd "%cd%" | clip

alternate methods-

If your path does not contain any space, you could do it with the one liner -

for /f "tokens=3" %%i in ('dir ^|findstr /i /c:"directory of"') do (echo.cd "%%i"| clip)

If it contains any space(s) -

for /f "delims=" %%i in ('dir ^| findstr /i /c:"Directory of"') do set mypath=%%i
set mypath=%mypath: Directory of =%
echo.cd "%mypath%"| clip

Cheers, G

gbabu
  • 1,088
  • 11
  • 15