Search code examples
batch-filecmddosdoskey

windows cmd(clink) doskey, how to copy the current directory to clipboard, prepended by "cd"?


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?


Solution

  • 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