First, some basics about directory stack:
1. Show directory stack with indices:
$ dirs -v
The top directory, i.e. the one with index=0, is the current working directory. On the other hand,
$ dirs [-N | +N]
where -N (+N) will show the Nth directory from bottom (top) where the entry at bottom (top) has index=0.
2. Add a directory, dir, to the stack
$ pushd -n dir
which puts dir (index=1) just below the current working directory (index=0) but above all others in the stack. If the
-n is missing, pushd will change the working directory to dir thus causing dir to have index 0 and all other directories to be pushed down the stack.
3. Go to the Nth directory from the top without changing the relative positions of the entries in the stack:
$ pushd +N
“rolls up” the stack to bring the directory with index N on top so that now it has index 0 (the indices of other directories in the stack change accordingly so as to keep the relative positions fixed).
4. Effect of
cd: substitute the top directory with another_directory:
$ cd another_directory
will replace the top direcotry (index=0) with another_direcotory, as well as you’ll be taken to another_directory.
5. Remove an entry from the directory stack:
$ popd +N
will remove directory with index N counting from top (first is always 0) from the stack. If you remove the top directory (i.e. the working directory, i.e. the one with index 0) you’ll be automatically taken to the next directory in the stack, whose index then will become 0.
Tilde Expansion [link]
$ echo ~N # same as: echo `dirs +N`
$ echo ~+N # same as: echo `dirs +N`
$ echo ~-N # same as: echo `dirs -N`
$ cd ~N
will replace the top directory with the Nth directory (without any other change in the stack). The same effect may be invoked by
$ pushd -n +N