Efficient command line navigation : pushd, popd and dirs
How do you navigate the command line like a pro.
When I was first exposed to the CLI, cd (change directory) and pwd (print working directory) were the two commands I learned for navigation and over time I haven’t really used anything else. These commands get the job done all the time for me so I didn’t even think if there are other ways to navigate the CLI.
That changed, when I started to read, debug and modify massive build scripts. Build scripts are often executed when packaging software with Docker. An example of a build script could involve fetching latest versions of multiple tools like go, swagger and grpc, generating client or server stubs, compiling your code, building a executable and cleaning up any temporary directories that have been created or zip files that have been downloaded. As more tools are added to the script, you would need some organization of your code and it could quickly turn into a complex directory structure that you will have to navigate to install the tools in their proper directories.
This is where pushd and popd come in. Instead of having to use cd to go forward a few folders and having to remember to use ../ the correct number of times to go back, pushd and popd make use of a stack.
dirs — When you run dirs, it shows the contents of the stack top to bottom from left to right. By default, the only entry in the stack is the current directory. This is also a handy tool to debug which directory you’re currently in if you’re having incorrect directory or directory doesn’t exist errors.
pushd — When you run pushd build/client/stub, the ~/dev/repository/build/client/stub directory is pushed on top of stack and your working directory changes to that directory. From here, you can push another directory onto the stack and that would be inserted at the top and the working directory changed to that location.
popd — When you run popd, the topmost entry from the stack is deleted and your working directory changes to the now top entry (you could have run popd from any other directory too and the end result of the stack would still have been the same).
There is a small difference here to the way a stack normally operates. By default, even before running any pushd or popd commands, the stack isn’t actually empty. There will always be one entry in the stack which is the current working directory. But if you try to pop this entry, you will get a directory stack empty error. This is because the working directory is always on the stack and cannot be popped off.
PS: I also never knew you can do CNTRL + F search in a terminal. Seems so obvious yet I never tried before ¯\_(ツ)_/¯