How to eliminate typing the search query twice in this one-liner (search for something)?

git grep "search for something" $(git log -g --pretty=format:%h -S"search for something")

My solution:

Create bash script /usr/local/bin/git-search:

git grep $search_string $(git log -g --pretty=format:%h -S$search_string)

Then I can use:

git search 'search for something'

You can put the following in a file and then source that file in your ~/.bashrc:

function gitgrep {
    git grep "search for something" $(git log -g --pretty=format:%h -S"$1")

To source it you would just have period filename . file_with_function

Then you would:

gitgrep "foo bar baz" (Quotes needed, could play with $@ instead of $1 if you don't want to use the quotes)

|improve this answer|||||

You can make that as an alias:

alias youralias="git grep \"$0\" $(git log -g --pretty=format:%h -S\"$0\")"

And then call it from shell like

youralias "search for something"

Does that work for you?

|improve this answer|||||
  • 2
    I thought that, according to the bash (alias) man, There is no mechanism for using arguments in the replacement text. If arguments are needed, a shell function should be used. – Ring Ø Aug 26 '10 at 12:32
  • 1
    So that little gotcha is why I had a strange feeling that something is wrong while I was typing up my tip. Kyle got it right. – Janne Pikkarainen Aug 26 '10 at 12:42

another option is to use bash history expansion:

git grep "search for something" $(git log -g --pretty=format:%h -S!#:2)
|improve this answer|||||

While all these will work, if you are also wanting to shorten your base commands for git, just create a file in ~/.gitconfig and add some aliases. For example, here are some of mine:

$ cat ~/.gitconfig
   ci = commit
   co = checkout
   f = fetch
   s = status
   b = branch
   d = diff
   a = add
   l = log
   g = grep

So now, you could issue the following:

git g "search for something" $(git l -g --pretty=format:%h -S"search for something")

OR you could still have the git aliases in your .gitconfig file, but also incorporate other peoples bash functions, aliases, etc that were proposed in this thread.

|improve this answer|||||
  • Alias would be good, but for the whole command. Actually, alias with parameters. Unfortunately I don't know how to shorten this to: git g 'search for something' using alias. See update to my question for alternative solution. – takeshin Aug 28 '10 at 7:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.