How to Search Git branches for a File or Directory
Read this tutorial and learn what are the basic git commands that can suggest a solution to the problem of searching for a file of a directory by a path.
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 log and git branch, come to the rescue to solve this problem. Here are the steps:
Finding commits that touched the file
Firstly, run the <kbd class="highlighted">git log</kbd> command followed by the <kbd class="highlighted">--all</kbd> flag and the file path:
git log
git log --all -- somefilecommit 45d3068b072c04d57c6b3d72679da7529564a4
Author: W3Docs <[email protected]>
Date: Fri Nov 21 16:4:22 2018 -0700
added somefileFinding branches containing the commit
Then, run the <kbd class="highlighted">git branch</kbd> command appending the <kbd class="highlighted">--contains</kbd> option, which displays only the branches that contain the specified git commit hash:
git branch
git branch -a --contains 45d3068
otherbranchYou can use glob patterns with git log to search for files in nested directories. Wrap the pattern in single quotes to prevent the shell from expanding it:
git log --all -- '**/my_file.png'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:
- Navigate to the repository on GitHub.
- Click on the "Code" button to see the repository's code.
- Click on the "Branch: [default branch]" dropdown menu and select "All branches".
- Type the name of the file or directory you want to search for in the search box.
- 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.
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 <kbd class="highlighted">git log</kbd> only works on the committed history in comparison with git status, which controls the working directory and the staging area.