How to Search Git branches for a File or Directory

  1. Steps to finding branches for a file or directory
    1. Viewing history
    2. Displaying commits
  2. What is Globbing
  3. The git log Command

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 <w3docs@doc.net>
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.

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.


Do you find this helpful?

Related articles