14.6 The Shells' pushd and popd Commands
How often do you need to move to some other directory temporarily, look at some file, and then move back to the directory where you started? If you're like most users, you do this all the time. csh and bash have pushd and popd commands make this a lot easier. (If you use ksh , O'Reilly & Associates' Learning the Korn Shell shows you shell functions that do the same thing.)
These commands implement a "directory stack." The classical analogy for a stack is one of those spring-loaded plate stackers in a school cafeteria. The last plate put ("pushed") onto the stack is the first plate taken ("popped") from the stack. It's just the same with directories: each time you use pushd , the shell adds your current directory to the stack and moves you to the new directory. When you use popd , the shell takes the top directory off the stack, and moves you to the directory underneath.
You may as well learn about pushd the way I did: by watching. Let's say that I'm in the directory ~/power , working on this book. I want to change to my Mail directory briefly, to look at some old correspondence. Here's how: 
pushd prints the entire stack, giving me some confirmation about where I am, and where I can go. When I'm done reading the old mail, I want to move back:
We're back where we started; the Mail directory is no longer on the stack.
What if you want to move back and forth repeatedly? pushd , with no arguments, just switches the two top directories on the stack. Like this:
And so on.
If you like, you can let your directory stack get really long.
this case, two special commands are useful.
The dirs command prints the directory stack. It's a good way to find out where you are. Some people like to put the dirs command in their prompt (7.11 ) , but I personally find incredibly long prompts more annoying than helpful.
The one drawback to pushd and popd is that you can easily build up a gigantic directory stack full of useless directories. I suppose this doesn't really hurt anything, but it's needless clutter. The only way to clear the stack is to popd repeatedly (except, in tcsh , the command dirs -c clears the stack). More to the point, the directories you're most likely to want are at the top of the stack. There's no really convenient way to save them. I mean, with 7 directories in the stack, you could conceivably do something like:
to get rid of the bottom two elements. The pushd moves the bottom two elements of a 7-directory stack to the top. A bit inconvenient. [Clearing the whole stack is a good use for the C shell repeat (9.25 ) command. For example, if the stack has 7 directories, type:
That's an easy way to start over when the stack gets too messy. –JP ]
has a savedirs
shell variable (6.8
If you set savedirs
will save your directory stack to the