Git Commit

Committing is how you permanently save a snapshot of your staged changes to the project's history, along with a message explaining what changed and why.

Recording Changes with git commit

Once changes are staged with git add, git commit takes everything in the staging area and saves it as a new, permanent point in the project's history. The -m flag lets you supply the commit message inline, which is the fastest way to commit from the terminal.

Example

$ git add script.js
$ git commit -m "Add form validation"
[main 7c1e4a2] Add form validation
 1 file changed, 12 insertions(+)

Writing Good Commit Messages

A commit message is a note to your future self and to every teammate who reads the history later. A good message explains what changed and, more importantly, why, since the diff itself already shows what changed line by line.

  • Use the imperative mood: "Fix login bug", not "Fixed login bug" or "Fixes login bug"
  • Keep the first line under about 50 characters
  • Leave a blank line before a longer explanation if one is needed
  • Describe why the change was made, not just what changed
  • Commit one logical change at a time rather than bundling unrelated edits

Viewing History with git log

Every commit you create is recorded permanently and can be reviewed with git log. Each entry shows a unique commit hash, the author, the date, and the commit message, newest first.

Example

$ git log
commit 7c1e4a2f9b8d3e5a1f0c2b4d6e8f0a1b2c3d4e5f
Author: Ada Lovelace <ada@example.com>
Date:   Tue Jul 14 10:15:32 2026 +0530

    Add form validation

commit 3f2a1c9e7d6b5a4938271605f4e3d2c1b0a9f8e7
Author: Ada Lovelace <ada@example.com>
Date:   Mon Jul 13 09:02:11 2026 +0530

    Add project README

Example

$ git log --oneline
7c1e4a2 Add form validation
3f2a1c9 Add project README
Note: Each commit hash is generated from the content of the commit and everything before it, which is why it looks like a random string of letters and numbers. You rarely need to type the whole hash; the first 7 characters are almost always enough to identify a commit uniquely.

Amending the Last Commit

If you notice a typo in your last commit message, or forgot to include a file, git commit --amend lets you fix the most recent commit instead of creating a brand new one. Amending replaces the previous commit entirely, so it should only be used on commits that have not yet been shared with anyone else.

CommandEffect
git commit -m "msg"Create a new commit from staged changes
git commit --amend -m "new msg"Replace the last commit's message and contents
git logShow full commit history
git log --onelineShow a compact, one-line-per-commit summary
Note: Never amend a commit that has already been pushed and pulled by someone else. Amending rewrites history by creating a brand new commit hash, which can cause serious conflicts for anyone who already has the old version.

Exercise: Git Commit

What does a Git commit primarily represent?