Previous working directory in Windows Command Prompt

Using bash in *nix has a handy feature: If you are in one directory and you switch to another one, you can use  cd -  to go back to the previous directory. My everyday computer is Windows 11 and I was longing to have that ability. I went back to an old tool called DOSKEY that was originally released in 1991 with MS-DOS 5. It's still around 33 years later (as of this writing).

One of doskey’s features is macros. They are roughly equivalent to aliases in *nix. Here's how I made something close to   cd -  work:
  1. Edit your registry to set a program to auto-run whenver you open a cmd.exe shell. Do this by adding a new String value to HKLM\SOFTWARE\Microsoft\Command Processor called Autorun. Put your program in as the Value data. In my example, I use "C:\Batch\cmd.cmd"


  2. I have a line in that file:
    doskey /macrofile=c:\batch\doskey.macros
  3. In the doskey.macros file, I have the following contents:
    cd = set OLDPWD=%CD% & cd $*
    cd- = set OLDPWD=%CD% & cd %OLDPWD%

It's not exactly equivalent to  cd - , but pretty close... just leave out the space between cd and -. Note that if you change directories without using cd and a space, for example by using the chdir command or by using  cd..  (with no space), it will break the   cd-  hack.

No comments:

Post a Comment

Previous working directory in Windows Command Prompt

Using bash in *nix has a handy feature: If you are in one directory and you switch to another one, you can use   cd -  to go back to the pr...