Keeping track of directories using pushd and pop

April 19, 2024

It can sometimes be hard navigate a number of directories across your filesystem, say you’re working on a personal project at the same time as a $WORK project. Usually, you’d use something like tmux or screen to have a separate workspace for each. This can work in graphical environments, but if you’re only at a tty then you’re stuck with the screen space you have. By using our friend, the stack, we can quickly navigate a number of directories from within the shell. Learning this should take only a few minutes, but the time saved (and boredom of typing cd) will save you hours over a year.

Pushd

Let’s say we have the following folders

~/code/work/lib/
~/code/work/app/
~/code/personal/

By default your current working directory is at the top of the stack. The current state of the stack, for each shell, can be found by running dirs. If you’re a visual person like me, you can add the -v flag to get a top-down view of the stack. Helpfully, this also includes the index of each directory.

$ dirs -v
 0  ~/code/personal
 1  ~/code/work/app
 2  ~/code/work/lib
 3  ~/code

Whilst working on all these projects we need to edit our nvim config file at: ~/.config/nvim/init.lua. We now can pushd to the directory.

$ pushd ~/.config/nvim
~/.config/nvim ~/code/personal ~/code/work/app ~/code/work/lib ~/code

As you can see, pushd adds the directory onto the stack, cds to that directory and then prints out the current state of the stack. The current directory is the left-most directory when using the commands and the top-most when using dirs.

Popd

After we’ve made the greatest ever change to our nvim lua file, it’s time to finish off our personal Haskell project.

$ popd
~/code/personal ~/code/work/app ~/code/work/lib ~/code

popd behaves in the same way as pushd, but instead of adding a directory to the stack we now pop it from the stack. The process is as follows: pop the top-most directory from the stack, cd to the pop’d directory and finally print the state of the stack.

We can double check the state of the stack using dirs:

$ dirs -v
 0  ~/code/personal
 1  ~/code/work/app
 2  ~/code/work/lib
 3  ~/code

Navigating back to $WORK is another popd command. Eventually you’ll reach the end of the stack, but you can build it up again by simply using pushd.

Replacement for cd:

An interesting feature of pushd is that it in rotates the top two directories in the stack when you supply it with no arguments, this is similar to how cd - behaves. There are additional toggles I suggest you research such as -N. You can find out more about each command, just by supplying --help to pushd.

Back to top