1

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:

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

Then I can use:

git search 'search for something'

4 Answers 4

4

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)

1

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?

2
  • 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.
    – Déjà vu
    Aug 26, 2010 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. Aug 26, 2010 at 12:42
1

another option is to use bash history expansion:

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

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
[alias]
   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.

1
  • 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, 2010 at 7:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .