Saving time when navigating directories at the Command Prompt using pushd and popd

It’s been a little while since I posted one of my favorite command line ‘tricks’…

Windows XP (NT/2000/2003/etc) has two commands (pushd and popd) that save me huge amounts of time when navigating my machine’s file system from a Command Prompt window.  What these handy commands do is to create a virtual stack where you can use to store where you have been and quickly return as needed.  This directory stack is structured First In-Last Out (FILO), so if you push several directories and wish to return to the origin, you will need to pop each one off of the stack, in reverse order, until you are back to the start — at which time the stack will be empty.

A very handy use of pushd is to wrap it with a cd (chdir) command in a doskey macro to create a custom command that changes the current directory while remembering where you started — this is how I most often use pushd. 

The doskey command reference (see the Microsoft Windows XP – Command-line reference link, below) states that you can create macros consisting of multiple commands as shown below
c:\>doskey tools=pushd .$tcd /d c:\tools

Please note that while the above illustrates using doskey to register a single macro, you can store all of your macros in one file and load them all at once using
doskey /macrofile <filename>

While this is a handy feature, the example above will result in two prompts being shown (one each for the pushd and the cd commands)
C:\Documents and Settings>tools

C:\Documents and Settings>

That can get a little confusing, and clutters up the Command Prompt window a bit.  To avoid the ‘double prompting’, I create a batch file (cdpush.bat) that disables echo before does the pushd and cd commands
@echo off
pushd .
cd /d %1

The @ sign in front of echo causes cmd.exe (and in MS-DOS) to suppress the echoing of the command to the screen.  The /d argument to the cd command allows it to change the drive as well as the directory.

The new tools macro now gets declared as
c:\>doskey tools=cdpush.bat c:\tools

Now, using our macro looks like this
C:\Documents and Settings>tools


Much cleaner, and you can use this batch file in other macros to change to any directory (with a pushd of your current location).

To return to my previous directory (at the top of the virtual stack) I type

And I am back to where I started
C:\Documents and Settings>

Another place where pushd and popd are handy is in batch files that need to change your current directory.  The Microsoft Windows XP – Command-line reference A-Z provides a very nice example.

— DK

[Edit(s): fix formatting]

This posting is provided “AS IS” with no warranties, and confers no rights.

Comments (0)