Switching directories on Unix quickly
How often do you find yourself bashing ..
at the prompt in hopes of getting to the correct directory? I don’t know about you but I used to do this a lot, I used to constantly switch directories only to find out I was in the wrong one or I’m a level deep and I had to immediately back-up ..
. So, I started looking for ways that would help me switch directories more easily. I came across this tool z
which is a good alternative but It didn’t felt intuitive enough, you had to hope it would guess the right directory.
I came up with a simple trick that has worked well enough for me for quite some time now, it’s intuitive and configurable.
Function
This is a simple bash function with find
and fzf
. Load this up in your .zshrc
. Follow along to get a grip on how this actually works.
quick_find() {
dir=$(find ~/programming -maxdepth 1 -type d -not -path '*/\.*' | fzf --height 40%)
if [ -n "$dir" ]; then
cd "$dir"
fi
}
# Bind the function to Ctrl+p
bind -x '"\C-p": quick_find'
Let’s go over each and every element in the function defined above.
1 find
: find helps you find files and directories on your system. Here, we’re doing a search for all the directories (-type d
) in the programming
directory (this is just me, you can add more directories in which you want to lookup). Next, we’re making sure that hidden directories don’t show up (-not-path '*/\.*
). And finally we make it a rule that the depth to which find should look for directories is just 1 level deep, that means it won’t go into a subdirectory, say subdir
which resides ~/programming/dir/subdir
, which is actually 2 levels deep.
2 fzf
: You probably already know about fzf
it, but if you don’t, it’s a fuzzy file finder that is really fast. We pass the results from find
which is nothing but a list of directories to fzf
which opens up a nice little interface where we can get suggestions as soon as we start typing, refer to the gif below.
3 cd $dir
: Finally, cd
into the selected directory. A note here, you need to hit the control return (enter) key for the cd to take effect, I’ve been looking into the why of this but couldn’t find a plausible explanation. Hit me up if you have something of value in this context
Conclusion
If all goes well, it gets easier to switch between directories easily. Also, if you can think of improvements to this please feel free to contact me via email.