Run `git commit -m` with single quotes in zsh
I sometimes use characters such as ! and $ in commit messages, they need to be manually escaped, but not if you use single quotes like this git commit -m 'My $message here!'
. I tried to write a function to make gc
and all text following as the message, but no luck in making it use single quotes. Everything I’ve tried, it still seems to use double-quotes in the end, making the $message
part hidden, and !
won’t work either.
I’ve tried this:
gc() {
git commit -m ''$*''
}
Also this:
gc() {
message="$*"
git commit -m ''$message''
}
Tried other things too that didn’t work, when checking git log
words starting with $
are not shown in the message. It works with single quotes, but it’s using double anyway.
I want to run gc My $message here
all text after gc
should be the message, I can’t force it to use single quotes, it ends up double. It would output My here
only.
Is there a way to write this function so it would work the way I want? Not sure if this is possible, thanks!
If there is you’re smarter than Bard, ChatGPT, Claude, and Bing AI, because I asked them all too, for several hours had no luck.
TL,DR: don’t.
What you’re asking for is impossible. When you write gc My $message here
, this is an instruction to expand the value of the variable message
and use the expansion as part of the arguments of the function.
You can do something like what you want by tricking the shell with an alias that adds a comment marker and calls a function that reads the comment from the shell history. This allows the function to receive arbitrary characters except newlines.
setopt interactive_comments
alias gc='gc_function #'
function gc_function {
emulate -LR zsh
setopt extended_glob
local msg=${history[$HISTCMD]#*[[:space:]]##}
git commit -m "$msg"
}
This is not (and cannot be) fully robust. The version I posted requires a space or other blank character after gc
; if you use a different non-word-constituent character, the commit message might not be what you expect.
I do not recommend this. You’re making it easy to write a one-line commit message, and hard to write a good commit message. A good commit message explains what the commit does and how. A good commit message is written in an editor. If you write one-line commit messages, you’re doing it wrong and you will regret it.