Skip to content Skip to navigation

pushd, dirs, and popd

If you spend a lot of your day at the command line (as I do), you're constantly on the lookout for new tools and tricks to increase your productivity and efficiency. Today we're going to take a look at the pushd suite of commands that exist in most shells (e.g., bash, tcsh and so forth).

What Do These Commands Do?

pushd, dirs, and popd help you move around your directory structure more efficiently. In short, they are cd on steroids.

Command Usage

cd

cd is pretty straightforward, and limited. cd <directoryname> to switch to that directory; cd - to switch back to where you were previously.

  ~$ cd /Applications/
  /Applications$ cd -
  /Users/jbickar
  ~$
 

pushd

pushd allows you to save a series of directories in your history, and later navigate back to any directory in the history. It also echoes, in a single line, what's in the history (or "stack"):

  ~$ pushd /Applications
  /Applications ~
  /Applications$
 

The above command, pushd /Applications, set /Applications as my current working directory, and echoed back the two directories in the stack, /Applications and ~, separated by a space.

Add a few more locations into the stack by using pushd some more:

  /Applications$ pushd /Users
  /Users /Applications ~
  /Users$ pushd /Applications/Utilities/
  /Applications/Utilities /Users /Applications ~
  /Applications/Utilities$
 

dirs

Use the dirs command to view what's in your history.

  /Applications/Utilities$ dirs -v
   0  /Applications/Utilities
   1  /Users
   2  /Applications
   3  ~
 

Then use pushd +n to navigate to the nth item in your history:

/Applications/Utilities$ pushd +2
/Applications ~ /Applications/Utilities /Users
/Applications$ dirs -v
 0  /Applications
 1  ~
 2  /Applications/Utilities
 3  /Users
/Applications$ pushd +1
~ /Applications/Utilities /Users /Applications
~$

popd

Use popd to remove the top location in the history (which is index 0, or where you currently are) and return to the previous location (which is index 1):

/Applications/Utilities$ dirs -v
 0  /Applications/Utilities
 1  /Users
 2  /Applications
 3  ~
/Applications/Utilities$ popd
/Users /Applications ~
/Users$

pushd in a Terminal window

Thanks to JB Christy in University Communications for introducing me to the pushd commands!

Further Reading

Categories: