Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I search Git branches for a file or directory?

Tags:

git

branch

In Git, how could I search for a file or directory by path across a number of branches?

I've written something in a branch, but I don't remember which one. Now I need to find it.

Clarification: I'm looking for a file which I created on one of my branches. I'd like to find it by path, and not by its contents, as I don't remember what the contents are.

like image 633
Peeja Avatar asked Dec 16 '08 20:12

Peeja


People also ask

How do I search all branches?

Git includes a grep command to search through commits to a repo as well as the local files in the repo directory: git grep. Sometimes it is useful to search for a string throughout an entire repo, e.g. to find where an error message is produced.


2 Answers

git log + git branch will find it for you:

% git log --all -- somefile  commit 55d2069a092e07c56a6b4d321509ba7620664c63 Author: Dustin Sallings <[email protected]> Date:   Tue Dec 16 14:16:22 2008 -0800      added somefile   % git branch -a --contains 55d2069   otherbranch 

Supports globbing, too:

% git log --all -- '**/my_file.png' 

The single quotes are necessary (at least if using the Bash shell) so the shell passes the glob pattern to git unchanged, instead of expanding it (just like with Unix find).

like image 129
Dustin Avatar answered Sep 20 '22 15:09

Dustin


git ls-tree might help. To search across all existing branches:

for branch in `git for-each-ref --format="%(refname)" refs/heads`; do   echo $branch :; git ls-tree -r --name-only $branch | grep '<foo>' done 

The advantage of this is that you can also search with regular expressions for the file name.

like image 31
ididak Avatar answered Sep 18 '22 15:09

ididak