Navigate to Previous Directory in Windows Command Prompt

Is there any command / tool to navigate previous directory in windows command prompt?

In linux usually use

cd -

for previous directory navigation.

Save the following to eg. mycd.bat somewhere in your path:

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

Then always remember to use mycd instead of cd to change directories and drives.

Alternatively, use a doskey macro:

C:\>doskey cd=mycd $*

The only caveat is if you omit the space between cd and .. or \, you will get the builtin version of cd not the doskey macro... and you still have to remember not to use C:, D: etc. to change drive.

4

You can use pushd and popd:

C:\WINDOWS>pushd \
C:\>popd
C:\WINDOWS>
4

if you are running the batch file you can use

  cd /D  %~dp0

This will jump back to the original path from where the batch file was run

If you want the exact behavior of bash, why not use bash? I have cygwin installed and it is very nice. It doesn't make you stick to its UNIX tools - it will happily call any windows executable. For cmd.exe builtins you can create an alias:

hugh@comp07 ~/testdir                             
$ alias cm='cmd /c'                               

hugh@comp07 ~/testdir                             
$ cm dir                                          
 Volume in drive C has no label.                  
 Volume Serial Number is AC2A-8378                

 Directory of C:\cygwin\home\hugh\testdir         

18/05/2010  02:02 PM    <DIR>          .          
18/05/2010  02:02 PM    <DIR>          ..         
               0 File(s)              0 bytes     
               2 Dir(s)   1,365,155,840 bytes free

hugh@comp07 ~/testdir                             
$ 

There's a freeware cmd clone with extra features including cd - called Take Command Console LE.

4

Depending what your goal is, you could just start a new cmd session by doing 'cmd', move directory and do whatever you want, when you then do 'exit' to leave the session you'll be back in the directory you were when you started the new session.

The accepted answer is very great for the requirement. While I often have to switch among many recent directories instead of just just two (current and previous).

So I recently made a batch to make my daily jobs easier.

1

What I do is

rem capture the path of the initial dir
set RET_DIR=%CD%
rem do stuff...
rem and then return to the initial dir
cd %RET_DIR%
Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest