Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to git grep in the whole tree when I'm in a subdirectory?

Tags:

git

grep

Normally when I issue git grep, it will only search the current directory and below, for instance

$ cat A
1
$ cd d
$ cat B
1
$ git grep 1
B:1
$ cd ..;git grep 1
A:1
B:1

How can I tell git grep "search the entire tree, no matter the current working directory I'm in"?

like image 241
Chi-Lan Avatar asked Jun 03 '12 07:06

Chi-Lan


People also ask

How do I grep all files in subdirectories?

To include all subdirectories in a search, add the -r operator to the grep command. This command prints the matches for all files in the current directory, subdirectories, and the exact path with the filename.

How do you grep a string in a directory and all its subdirectories?

To grep All Files in a Directory Recursively, we need to use -R option. When -R options is used, The Linux grep command will search given string in the specified directory and subdirectories inside that directory. If no folder name is given, grep command will search the string inside the current working directory.

Does git grep search all branches?

Moreover, git grep can search in a specific commit, branch, or even find all the occurrences between two commits or tags in the repo.

How do I grep all files in a directory in Linux?

You can make grep search in all the files and all the subdirectories of the current directory using the -r recursive search option: grep -r search_term .


1 Answers

Git aliases that run shell commands are always executed in the top level directory (see the git config man page), so you can add this to your .gitconfig file:

[alias]
    rgrep = !git grep

Alternatively, you could use git rev-parse --show-toplevel to get the root directory, which you could then pass to git grep as the basis of a script or alias:

git grep $pattern -- `git rev-parse --show-toplevel`
like image 92
georgebrock Avatar answered Oct 18 '22 10:10

georgebrock