Skip to content

Instantly share code, notes, and snippets.

@vijayhardaha
Created September 24, 2023 18:59
Show Gist options
  • Save vijayhardaha/6bf6b5795f14493fe1022afdad2cebc0 to your computer and use it in GitHub Desktop.
Save vijayhardaha/6bf6b5795f14493fe1022afdad2cebc0 to your computer and use it in GitHub Desktop.
Find All Git Repositories in a directory using the Command Line

Find All Git Repositories within a directory using the Command Line

When working with multiple Git repositories in various directories, it's helpful to quickly locate them within the command line. This custom shell function, find-git-dirs(), allows you to search for all Git repositories in the current directory and its subdirectories.

How to Use the Function in Your Shell Configuration Files

You can add the find-git-dirs() function to your shell configuration files (.bashrc, .bash_profile, or .zshrc) to make it available each time you start a new terminal session. Here's how to add and utilize the function in your shell configuration:

  1. Open Visual Studio Code or your preferred code editor.

  2. For Bash (.bashrc or .bash_profile) and Zsh (.zshrc):

    a. Bash Configuration: If you're using Bash, open your Bash configuration file. Depending on your system, it might be either ~/.bashrc or ~/.bash_profile.

    b. Zsh Configuration: If you're using Zsh, open your Zsh configuration file, typically ~/.zshrc.

  3. Copy and Paste: Copy and paste the following shell function at the end of your configuration file:

    # Function to find all Git repositories in the current directory and its subdirectories
    find-git-dirs() {
        find ./ -name .git -type d -exec dirname {} \;
    }
  4. Save the Changes: Save the changes to your configuration file.

  5. Reload the Configuration:

    • For Bash: In your terminal, either restart your terminal or run:

      source ~/.bashrc
    • For Zsh: In your terminal, either restart your terminal or run:

      source ~/.zshrc
  6. Usage: You can now use the find-git-dirs function in your Bash or Zsh shell. Simply run it in any directory, and it will list the paths to all Git repositories within that directory and its subdirectories.

    find-git-dirs

Conclusion

By integrating the find-git-dirs function into your shell configuration, you can effortlessly locate all Git repositories in your command-line environment. This custom function is a valuable tool for managing and navigating your Git projects efficiently.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment