How to Search Git branches for a File or Directory

Different Git commands can help you get out of the situations quickly. There are times when you want to search for a file or directory but cannot remember its content. Git allows finding the exact file or directory by a path among a bunch of branches easier than you think.

Steps to finding branches for a file or directory

The two most frequent Git commands, namely git branch and git branch, come to the rescue to solve this problem. here are the steps:

Viewing history

Firstly, run thegit log command followed by the --all flag:

git log --all -- somefile
commit 45d3068b072c04d57c6b3d72679da7529564a4
Author: W3Docs <[email protected]>
Date:   Fri Nov 21 16:4:22 2018 -0700

    added somefile

Displaying commits

Then, run thegit branch command appending the --contains option which displays only the branches that contain the named git commit:

git branch -a --contains 55d2069
  otherbranch

This also supports globbing:

git log --all -- '**/my_file.png'
It is important to add the single quotes if using the Bash shell so as the shell passes the glob pattern to git not changed.

What is Globbing

Globbing is a programming concept describing the process of using wildcards, referred to as "glob patterns" or "globs", to match the file paths or other similar collection of strings. Globs are defined using wildcards, along with non-matching characters. They are similar to regular expressions but much simpler and limited in scope.

Using GitHub website:

To search for a file or directory in Git branches using the GitHub website:

  1. Navigate to the repository on GitHub.
  2. Click on the "Code" button to see the repository's code.
  3. Click on the "Branch: [default branch]" dropdown menu and select "All branches".
  4. Type the name of the file or directory you want to search for in the search box.
  5. Press Enter.

This will show you all instances of the file or directory in all branches of the repository. You can click on each file to view its contents and see which branch it belongs to.

Note that if you are searching for a file or directory that was recently added to the repository, it may take a few minutes for it to be indexed by GitHub's search feature.

A new PC with no local branches

If you are running on a new PC with no local branches, you can still use the GitHub website to search for files or directories in the repository. However, you may not be able to see the contents of the files or which branch they belong to until you clone the repository to your local machine and check out the appropriate branch.

The git log Command

The git log command displays committed snapshots. It is used for listing and filtering the project history, and searching for particular changes you have made. The git log only works on the committed history in comparison with git status, which controls the working directory and the staging area.