Moving Quickly Among Arbitrary Directories

Problem

Do you find yourself moving frequently between two or more directories? Are you changing directories to here, then there, and then back again? Do you tire of always typing long path names since the directories never seem to be close by?

Solution

Use the pushd and popd built-in commands to manage a stack of directory locations, and to switch between them easily. Here is a simple example:

$ cd /tmp/tank
$ pwd
/tmp/tank

$ pushd /var/log/cups
/var/log/cups /tmp/tank

$ pwd
/var/log/cups

$ ls
access_log error_log page_log

$ popd
/tmp/tank

$ ls
empty full

$ pushd /var/log/cups
/var/log/cups /tmp/tank

$ pushd
/tmp/tank /var/log/cups

$ pushd
/var/log/cups /tmp/tank

$ pushd
/tmp/tank /var/log/cups

$ dirs
/tmp/tank /var/log/cups

Discussion

Stacks are last in, first out mechanisms, which is how these commands behave. When you pushd to a new directory, it keeps the previous directory on a stack. Then when you popd, it pops the current location off of the stack and puts you back in that first location. When you change locations using these commands, they will print the values on the stack, left to right, corresponding to the top-to-bottom ordering of a stack.

If you pushd without any directory, it swaps the top item on the stack with the next one down, so that you can alternate between two directories using repeated pushd commands with no arguments. You can do the same thing using the cd - command.

You can still cd to locations—that will change the current ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.