Trying to create bash function which collects and quotes all arguments, but it doesn't work if args contain brackets or single quotes

2

I saw the following shortcut for "git commit" suggested somewhere:

function gc {
  git commit -m "$*"
}

This is supposed to allow you to write the commit message inline in the shell, without quotes or anything. Like:

gc This is a commit message

The problem is, it doesn't seem to work if the commit message itself contains brackets or quotes. (And I use a lot of brackets/quotes in my commit messages.) Can anyone well versed in the art of bash scripting suggest a better shortcut?

Alex D

Posted 2013-02-14T21:08:31.860

Reputation: 291

Answers

3

I don't think this is a problem with your function (or, more accurately, I don't think this is a problem you can solve in your function). bash parses the command line (including interpreting quoted strings, various bracket expressions, etc) before it calls your function -- before it even decides to call your function. So when you type something like gc fixed Greg's bug, bash will require that you close the quoted string before it executes the function; when you type gc printf("%s", integervar) not a good idea, bash will complain about the parentheses and never even get to the point of deciding what command/function/whatever was being requested.

I presume the point of using $* was to avoid having to quote the memo on the command line, but that only avoids having to quote spaces in the message. If the message contains other shell metacharacters, you must quote or escape them appropriately:

gc "fixed Greg's bug"
gc 'printf("%s", integervar) not a good idea'
gc 'fixed this & deferred that'

Gordon Davisson

Posted 2013-02-14T21:08:31.860

Reputation: 28 538