Go to content

geek_stuff/server & linux

How to fuzzy cd (change directory) to specific directory

I've been working on IT fields for more than decades and there are lots of code repositories and snippets.

It's all over in github, gitlab, bitbucket, and all different organizations.

 

When one day I realized I have all these repositories thrown into single folder ~/repo, then I decided to organize these folders by grouping them into company name.

~$ cd repo
~/repo$ ls
companyA companyB companyC companyD companyF github companyI mcysd personal
~/repo$

Inside of these companies, I have folders named by projects.

 

Looked neat, and easy to find folders, yet, it was painful everytime when I open new terminal and cd into directories.

 

So I wrote simple bash script to go to diretory easily using fzf

If you hanve't installed the fzf, install it first.

$ sudo apt install fzf

 

Then open ~/.bashrc with your favorite editor.

$ nano ~/.bashrc

 

Copy and paste this script in the end of the file and save it.

# This script performs search of specific directory up to 2 depth and change directory into it.
# This is helpful for cases like having many repositories and need to cd into it.

# Install
#   1. Install fzf(https://github.com/junegunn/fzf#related-projects). eg: sudo apt install fzf (
#   2. Copy this source and paste into paste into your: nano ~/.bashrc 
#   3. Edit the srchDir variable for your environment
#   4. Save and start new session of terminal

# Usage
#   $ repo term1 term2

# Script
#   Copy from bottom line to end and paste in the end of ~/.bashrc
repo() {
    # This will list up to 2 depth of given directory. Add/remove '*/' to your preferences.
    # The path should be absolute path.
    # Note that too many depth will slow-down the script, less depth will show fewer results.
    local srchDir="/home/your/repo/*/*/"

    # if any arguments arn't given, just list up everything else use search query
    [ "$1" = false ] && cd "$(ls -d $srchDir | fzf)" || local qTerm="${@}"; cd "$(ls -d $srchDir | fzf -q "$qTerm")"
}

 

This script will search directories and subdirectories up to 2-depth from startDir.
Change starting point by editing /home/ikko/repo/*/*/

You can rename function name repo to any name you want to.

You also can add more */ but I don't recommend for slowing down the script.

 

Now time to test new script,

$ repo bac


> /home/ikko/repo/github/IRKit-Javascript/
  /home/ikko/repo/github/UI_Automation_POC/
  /home/ikko/repo/github/bootstrap-daterangepicker/
  /home/ikko/repo/github/kakaotalk_chat_analysis/
  /home/ikko/repo/github/obsidian-clipper/
  5/106
> bac

 

That's it! Happy scripting!