SystematicFrank
SystematicFrank

Reputation: 17269

Shell function command with quotes

I am trying to make a git shortcut to commit with a message. Since aliases do not support parameters I came up with this function:

function gcm() { git commit -m "$@" }

My expectation is to commit with a message without even typing quotes like this:

gcm create cli module

However I get an error, probably due to the string interpolation when expanding the all-params symbol.

error: pathspec 'cli' did not match any file(s) known to git.
error: pathspec 'module' did not match any file(s) known to git.

How can I fix the function so I can have an alias that saves me from typing quotes?

UPDATE:

I love this shortcut so much that I must make a copy paste friendly version of the solution for everyone

alias gcm='function() { git commit -a -m "$*" }'

Upvotes: 3

Views: 94

Answers (2)

chepner
chepner

Reputation: 532333

Make your commit message a single argument, not a sequence of separate arguments.

gcm () { git commit -m "$1"; }

and invoke it like this:

gcm "My commit message"

This way, you get the exact text you type in your commit message, without the following happening:

  • Multiple consecutive spaces collapsed to one space
  • Other whitespace such as tabs and newlines converted to spaces
  • Characters like * would need to be quoted anyway to prevent special interpretation by the shell.
  • If the value of IFS is changed for some reason, it will affect the content of your commit message:

    $ gcm () { echo "$*"; }
    $ gcm my    commit message
    my commit message
    $ IFS=:
    $ gym my    commit message
    my:commit:message
    

Upvotes: 2

Etan Reisner
Etan Reisner

Reputation: 81052

You want "$*" not "$@" because you want the arguments expanded as a single word not multiple words.

This is one of the few times the "$*" expansion is actually desirable. It generally isn't.

Upvotes: 6

Related Questions