Git: Adding a Commit Message

As many programmers have found out the hard way, adding documentation is extremely important in being able to easily make modifications to your code, fix issues, pass off to others, etc. Just because your code makes sense now doesn't mean it'll make sense to you in 6 months (or even a week, really). You're probably used to documenting your actual code, but this same practice should also be followed with your version control commits as well.

In Git, there are a few ways to document your changes, but we'll be focusing mostly on how to do it for individual commits in this short article.

When viewing a repository on GitHub, you have probably noticed the messages next to a file or folder:

These messages are typically added to the repository at the time in which you make the commit, although you can retroactively add commit messages as well.

In GitHub, the message next to the file or folder is from the last commit in which that file/folder changed. So these are not all necessarily from the last commit. Otherwise it wouldn't be very useful if GitHub displayed the same commit message from the last commit for all files.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

In order to add this message, you need to specify the -m flag when executing git commit. Your message should immediately follow the flag and be wrapped in quotation marks. An example of this looks like this:

$ git commit index.js -m "Fixed world-ending bug (#281)"

Multi-Line Messages

You can't always describe a complex change with a short, single-line comment. An interesting feature of the -m flag is that you can add multiple paragraphs to your message by using the -m flag multiple times in the same commit command:

$ git commit index.js -m "My Changes" -m "- Fixed a critical bug" -m "- Probably added more bugs"

These multiple messages will then look like this in the resulting commit:

My Changes
- Fixed a critical bug
- Probably added more bugs

Another option, which depends on the shell you're using, is to just enter a single or double quote and press Enter, without closing the quote. This works well in Bash, which doesn't enter the command until you've closed the quote:

$ git commit index.js -m "My Changes
- Fixed a critical bug
- Probably added more bugs
"

And finally, you don't actually need to use the -m flag at all. If you omit this flag then Git will automatically open a text editor for you to enter the commit message.

Last Updated: February 26th, 2020
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms