Monolune

Making Git commits with less keystrokes

How many times do you run git commit in a day? If you are one of those people who like to make multiple small changes instead of huge one-off ones, you probably run git commit a lot. In this article, I will present a way to save yourself from having to type of git commit -am '...' every time you wish to commit. You can normally reduce the number of keystrokes needed by using a bash alias for git commit, but the method below makes use of shell functions instead (for reasons that will soon be clear).

git commit

function gc {
    if [ -z "$1" ]; then
        git commit  # Opens a text editor.
    else
        git commit --message "$*"
    fi
}

Adding this shell function to your ~/.bashrc or ~/.zshrc allows you to type gc instead of git commit, saving you valuable keystrokes. But that is not all. Instead of having to type git commit -m 'Initial commit', you can type gc Initial commit. Note that no quotes are necessary, further reducing the amount of keystrokes needed. Also notice that the behaviour depends on whether or not a commit message is supplied on the command line. If a message is not supplied, a text editor opens. This shell function has saved me from having to type out git commit every time.

git commit --all

The above shell function only does git commit, but what about git commit --all? For that, another shell function can be used:

function gca {
    if [ -z "$1" ]; then
        git commit --all
    else
        git commit --all --message "$*"
    fi
}

This allows the use of gca instead of git commit --all. A text editor will open depending on whether or not a commit message is supplied. As usual, it is not necessary to surround the commit message with quotes when the commit message is supplied through the command line. For example, gca Second commit is equivalent to git commit --all --message 'Second commit'.

To be able to use the shell functions defined above, restart the terminal, or run exec bash (or exec zsh if you are using ZSH as your shell).

Conclusion

Given the number of times that git commit is used in a day, it is worth taking some time to think about how the number of keystrokes can be reduced for making commits. I think the shell function approach presented above is an effective way of solving the problem.