Creating a Bash Command to Quickly Search Directories
Posted
When working in the command line, you often want to navigate to a directory containing a particular file. You might not remember where that file is, but if you remember the file name, or part of its name, you can easily find it by using fzf – the open source fuzzy finder.
To obtain a list of all directories within the active folder, you can run
find * -type d
where * is a wildcard and the -type parameter indicates what kind of file you are looking for (d is for directories). Find is typically installed by default on most Linux based OS. Find’s outputted list can then be searched by piping this list into fzf. By adding the cd command in front of all this, you can automatically jump to the file you’ve selected. Note that you may first need to install fzf using your package manager before you can make use of the following command.
cd find * -type d | fzf
To make an alias available for future use, append the following to your ~/.bashrc file.
1sd(){ #search directory.
2 cd "$(find * -type d | fzf)";
3}
4shd(){ #search the home directory
5 cd ~;
6 cd "$(find * -type d | fzf)";
7}
Open a new bash instance to reload the .bashrc file or by typing
source ~/.bashrc
bash