May 3, 2014
I just discovered a handy pair of Unix commands I didn't know about before: pushd and popd. Together they allow you to keep a stack of directories and push and pop it.
One use case where this is nice is if you are in one directory, say "~/projects/thing1" and you need to go some place else in the file system temporarily, then return to where you were. I seem to need to do this a lot.
If you know ahead of time what directory you need to go to, you can just cd to that directory, do whatever it is you need to do, then do "cd -" which returns to the previous directory. "cd -" is like the back button in a web browser.
Oftentimes, however, I don't know ahead of time where I need to go. Perhaps I'm searching for a log file, and don't know where it is, but want to start looking in /var/log, then cd into a sub-directory. Or maybe I need to find something in my home directory and don't remember where I put it. "cd -" can't be used because it only remembers the very last directory you were in.
Enter pushd and popd. If I know I want to come back to my current directory, I can just "pushd ." to add it on to the directory stack. Now I can cd all over the place and, when I want to return, executing the "popd" command will take me back!
$ pushd . ~/projects/thing $ cd /var/log $ cd apache2 $ popd ~/projects/thing
Since it's a stack, you could of course add multiple levels, but I can't imagine myself using that very often.
Copyright © 2022 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.