33

Suppose I have:

alias gg="git grep"

then stuff like:

gg "int x"

works, but

gg int x

gets complaints. Is there a way to rewrite gg as a function in zsh so that it takes all the arguments after gg, and stuffs them into a string?

Thanks!

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
anon
  • 41,035
  • 53
  • 197
  • 293

2 Answers2

60
gg() { git grep "$*"; }
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
  • 6
    Uhm, to have them go into one string, you need `"$*"` instead of `"$@"` -- the form you wrote would pass them through as separate params, just like the alias. – Phil P Mar 16 '10 at 20:08
  • 1
    This has the benefit of also being compatible with bash – Jian May 31 '13 at 16:31
6

For your particular use case, this is a bad idea. git-grep is expecting a single-arg pattern. You're trying to get the shell to treat your space (between int and x) as part of the pattern. This will break quickly when you try something like: gg foo.*bar or various other things that the shell might interpret. So anything after gg really should be quoted. This is why git grep int x also doesn't work: fatal: ambiguous argument 'x': unknown revision or path not in the working tree...

If you think gg is a worthwhile keystroke saver, you should keep your arg to it consistent with what git-grep expects. Your original alias is fine for this. And continue to single- or double-quote your pattern, just like you do with any other regex-accepting command.

Micah Elliott
  • 9,600
  • 5
  • 51
  • 54
  • On the one hand it is very reasonable for a person to say "I reject the artificial need to manually quote things in a use-case where it is unambiguous what I want", on the other hand it's setting up a pitfall for yourself if habitually getting away without quoting leads you to accidentally forget to quote other special shell characters. But a user is not necessarily wrong for choosing the former, especially if they're informed. – mtraceur Feb 08 '23 at 20:54