command-linecmddoskey

How can I return to the previous directory in windows command prompt?


I often want to return to the previous directory I was just in in cmd.exe, but windows does not have the "cd -" functionality of Unix. Also typing cd ../../.. is a lot of typing.

Is there a faster way to go up several directory levels?

And ideally return back afterwards?


Solution

  • Run cmd.exe using the /k switch and a starting batch file that invokes doskey to use an enhanced versions of the cd command.

    Here is a simple batch file to change directories to the first parameter (%1) passed in, and to remember the initial directory by calling pushd %1.

    md_autoruns.cmd:

    @echo off
    cd %1
    pushd %1
    title aliases active
    cls
    %SystemRoot%\System32\doskey.exe /macrofile=c:\tools\aliases
    

    We will also need a small helper batch file to remember the directory changes and to ignore changes to the same directory:

    mycd.bat:

    @echo off
    if '%*'=='' cd & exit /b
    if '%*'=='-' (
        cd /d %OLDPWD%
        set OLDPWD="%cd%"
    ) else (
        cd /d %*
        if not errorlevel 1 set OLDPWD="%cd%"
    )
    

    And a small aliases file showing what to do to make it all work:

    aliases:

    cd=C:\tools\mycd.bat $*
    cd\=c:\tools\mycd.bat ..
    A:=c:\tools\mycd.bat A:
    B:=c:\tools\mycd.bat B:
    C:=c:\tools\mycd.bat C:
    ...
    Z:=c:\tools\mycd.bat Z:
    .=cd
    ..=c:\tools\mycd.bat ..
    ...=c:\tools\mycd.bat ..\..
    ....=c:\tools\mycd.bat ..\..\..
    .....=c:\tools\mycd.bat ..\..\..\..
    ......=c:\tools\mycd.bat ..\..\..\..\..
    .......=c:\tools\mycd.bat ..\..\..\..\..\..
    ........=c:\tools\mycd.bat ..\..\..\..\..\..\..
    .........=c:\tools\mycd.bat ..\..\..\..\..\..\..\..
    tools=c:\tools\mycd.bat C:\tools
    wk=c:\tools\mycd.bat %WORKSPACE%
    

    Now you can go up a directory level by typing ..

    Add another . for each level you want to go up.

    When you want to go back, type cd - and you will be back where you started.

    Aliases to jump to directories like wk or tools (shown above) swiftly take you from location to location, are easy to create, and can really help if you work in the command line frequently.