previous contents up next

Unix for Advanced Users

5. Navigating effectively

5.10 How do I remember where I was last?

Unix programs tend to have many small files. Often, you will find yourself shuttling between two directories, repeatedly editing or moving related files. It quickly becomes tiresome to type the full directory name over and over again as you cd back and forth.

5.10.1. pushd and popd

Happily, both Bourne- and csh-derived shells provide a shortcut for this kind of movement. It works through a pair of built-in commands called pushd and popd. pushd saves a directory name for later recall, and popd changes to that directory. Thus, if you are editing a file in /etc/ and need to jump momentarily to /usr/lib, you can pushd . and then cd /usr/lib/. Once you are finished working in /usr/lib, you can popd to be restored to /etc/.

In fact, you can store more than one directory name at a time. If you use pushd twice without using popd in between, the next call you make to popd will restore you to the second directory you pushed. This is the meaning of the text messages printed by pushd and popd: It shows the directories that are saved, in order, with the one that will pop first on the left and the one that will pop last on the right.

5.10.2 dirs

An addition function, dirs, can be used to show the stack without changing it. The form in which directories are stored, with the first ones pushed being the last that are popped, is a common structure in computer science. It is called a stack. The analogy is to a physical stack of (e.g.) trays in a cafeteria, where the workers put trays on the top of the stack and the customers take them from the top of the stack. If several trays are pushed without anyone "popping" one, the later trays go on top of the earlier ones, so that the first tray to be pushed is the last to be popped off. A short mnemonic for this kind of action is FILO, which stands for "first in, last out". (There is also a FIFO, or first in, first out algorithm. Unix pipes show FIFO behavior.)

5.10.3. cd -

In addition to providing pushd and popd,
bash and ksh remember the last directory you used. Under those shells, the pushd-popd duo can often be substituted by cd -, which changes to the last working directory, and so is ideal for switching between two directories.

previous contents up next