Unix: Using pushd and popd for faster navigation

link to a Network World piece on pushd and popd, with a tl;dr on using the directory stack and rotating it with pushd +N

Unix: Using pushd and popd for faster navigation

The pushd and popd commands put directory paths onto a directory stack (pushd) and then pop them off again (popd). Using the pushd and popd commands is not unlike dropping directory “bread crumbs” and then returning in reverse order to all the places you visited.

TL;DR

pushd and popd manage a directory stack — cd with a memory. It’s LIFO: last in, first out.

  • pushd <dir> — changes into <dir> and pushes it onto the stack
  • popd — pops the top entry off the stack and changes into the next one
  • dirs — shows the current stack
 1$ pushd ~/dir1
 2~/dir1 ~
 3$ pushd ~/dir2
 4~/dir2 ~/dir1 ~
 5$ pushd ~/dir3
 6~/dir3 ~/dir2 ~/dir1 ~
 7
 8$ popd
 9~/dir2 ~/dir1 ~
10$ popd
11~/dir1 ~
12$ popd
13~

The leftmost entry is always your current directory.

Rotating the stack

pushd +N rotates the stack — moves the Nth entry to the top (and cds into it), without pushing anything new. Handy for cycling through a fixed set of directories.

1$ dirs
2~/dir3 ~/dir2 ~/dir1 ~
3$ pushd +1
4~/dir2 ~/dir1 ~ ~/dir3

When it’s useful

  • Jumping between 2–3 directories repeatedly (build dir, source dir, logs dir) without retyping paths
  • Not great for random access — if you need to jump around a lot, symlinks or $CDPATH are better fits