Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 78 ยท The Basic Workflow

Making Good Commits

Learn what a Git commit really is, how to use git commit, -a, --amend and --allow-empty, and how to write atomic commits with clear, conventional messages.

A commit is the unit of Git history. Everything else you will learn, from branches to bisecting, is built on commits, so it pays to understand what one is and what makes a good one. Technically a commit is a small object that points to a complete snapshot of your project, to its parent commit, and carries a message, an author and a date. Practically, a commit is a sentence in the story of your project. Future you, your teammates and tools such as git blame and git bisect will read that story for years.

In this lesson you will look inside a commit, learn the everyday options of git commit, fix a commit you just made with --amend, and learn how to write messages that people thank you for. It continues from Staging Changes, where you chose what goes into the next snapshot.

What is inside a commit

You can ask Git to print a commit's raw object with git cat-file -p. Run the example and read the output carefully.

Bash Anatomy of a commit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first line of output, [main (root-commit) c200134] Add hello.txt, is Git's receipt: the branch (main), the note root-commit (a commit with no parent), the short hash and the subject. The raw object has these parts:

Field Meaning
tree The ID of the snapshot: a tree object listing every file and folder in the project at that moment
parent The ID of the previous commit. The root commit has none; a merge commit has two
author Who wrote the change, with an email and a timestamp (here a Unix time such as 1767268800)
committer Who created the commit object, with a timestamp. Usually the same as the author, but different after a rebase, a cherry-pick or an applied patch
message Everything after the blank line

The commit hash (the 40-character ID, usually shown shortened) is a SHA-1 checksum of exactly that text. Change anything, such as one letter of the message or the parent, and you get a different hash. This is how Git detects corruption and why you can never really "edit" a commit; you can only create a new one. Because we fixed the names and dates with environment variables, you get exactly the same hashes as the ones in this lesson every time you run it. In real life the dates differ, so your hashes will too.

Notice also the tree line. Git does not store "what changed". It stores the whole snapshot (cheaply, because unchanged files are shared between snapshots). The diffs you see in git show are computed on demand by comparing a commit's tree with its parent's tree. The details are in How Git Works and the internals track starts at Git Objects.

The everyday forms of git commit

TEXT
git commit                    # opens your editor for the message
git commit -m "Subject"       # message on the command line
git commit -a -m "Subject"    # first stage all modified/deleted TRACKED files
git commit --amend            # replace the last commit
git commit --allow-empty      # commit even though nothing changed
git commit -v                 # show the diff in the editor while you write the message

In our browser sandbox there is no editor, so the examples always pass the message with -m or -F. On your own computer, running git commit without -m opens the editor you configured (see Installing and Configuring Git) and shows the staged files as comments. Add -v to also see the full diff there, which is a great way to review your work while you describe it.

Bash commit -a, --allow-empty and several -m flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Look at what happened:

  • git commit -a stages every modified or deleted tracked file automatically, which is the shortcut most people use day to day. It skips untracked files: untracked.txt is still ?? afterwards. It is the same as git add -u followed by git commit.
  • --allow-empty creates a commit with the same tree as its parent. Git normally refuses ("nothing to commit"). Empty commits are useful as markers, or to trigger CI (continuous integration) pipelines.
  • Every -m becomes a separate paragraph. The first is the subject, the rest form the body. That is the quickest way to write a multi-line message without an editor.
  • A commit with an empty message is aborted, and the exit code is 1.

git commit -a is convenient, but it commits every change to tracked files, including the debug print you forgot about. If you want clean commits, stage deliberately and review git diff --staged first.

Fixing the last commit with --amend

Typos happen. You forgot a file, or the message is wrong. git commit --amend replaces the most recent commit with a new one that has your staged changes and/or a new message. It does not edit the old commit: it builds a new one (new hash) and moves the branch to it.

Bash Amending the last commit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The old commit 90bd51d is gone from git log and the new one is bfd0680. The reflog (Git's private diary of where HEAD has been, see The Reflog) still lists all of them for a while, so an amend is recoverable. Useful variants:

  • git commit --amend --no-edit keeps the message and only adds the staged changes.
  • git commit --amend -m "New message" changes only the message (if nothing is staged).
  • --author="Name <email>" changes the author; the committer stays you, as the last line of output shows.

The golden rule: amend only commits you have not shared. Once someone else has your commit, a new hash means a different history, and you will make collaborators' lives difficult. For older commits see Interactive Rebase and Amending, Splitting and Rewriting Commits.

Atomic commits

An atomic commit contains one logical change and leaves the project in a working state. Not one file, not one line, but one idea: "Validate quantity in the cart", "Rename fetchData to loadUser", "Update the Docker base image".

Why it matters:

  • Review is easier. Reviewers can read one small, coherent diff instead of a mixture.
  • Bisecting works. git bisect (see Finding Bugs with git bisect) needs commits that build, or it cannot tell which one broke things.
  • Reverting is safe. If a feature breaks production, you can git revert exactly one commit without removing three unrelated fixes.
  • History explains itself. git log and git blame become documentation.

Signs a commit is not atomic: the message needs the word "and" ("Fix login and update styles and bump version"), or the diff mixes formatting changes with logic changes. Split such work using git add -p (see Staging Changes). Also avoid the opposite extreme: a commit per saved file, with messages such as "wip" and "fix", is just as useless. A commit is finished when its message can be written honestly in one short line.

Writing the message

A commit message has a subject, a blank line, and an optional body. The conventions are old and widely shared:

  1. Subject: about 50 characters, up to 72 at most, in the imperative mood ("Add", "Fix", "Remove", as if completing the sentence "If applied, this commit will ... "). No trailing period.
  2. Blank line between subject and body. Tools such as git log --oneline and email patches rely on it.
  3. Body: explain what and why, not how; the diff already shows how. Wrap lines at about 72 characters. Describe the problem, why this solution, and side effects or alternatives you rejected.
  4. Trailers at the end, such as Fixes: #42, Co-authored-by: or Reviewed-by:.
Bash A complete message and reading its parts back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git commit -F - reads the message from standard input, which is handy in scripts, and a quoted heredoc (<<'MSG') keeps the text exactly as written. git log indents the message by four spaces for display. The format placeholders %s (subject), %b (body) and %(trailers:...) let you pick the parts out, which is how release tools build changelogs from your messages.

Why the body matters

The diff tells you what changed. Only the author can tell the reader why: "the payment step refunded negative totals" is information that exists nowhere else. Six months later, when someone wonders whether the check is still needed, that paragraph is worth more than the code. A good rule: if you had to think for more than a minute while making the change, the thinking belongs in the body.

Conventional Commits

Many teams add a machine-readable prefix to the subject. The popular format is Conventional Commits: type(scope): description, with a ! after the type or a BREAKING CHANGE: trailer for incompatible changes. Common types are feat (a new feature), fix, docs, refactor, test and chore. It lets tools pick the next version number and generate changelogs automatically (see Tags and Releases). Here is a tiny checker you could put in a hook (see Git Hooks):

Bash Checking subjects against Conventional Commits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The regular expression requires a known type, an optional scope in parentheses, an optional !, a colon and space, and then 1 to 60 characters of description. "Fixed stuff" fails because it has no type, and the last one fails because the description is empty. Conventional Commits is a team decision: adopt it if you automate releases, skip it if nobody would use it. The imperative, focused subject is worth having either way.

Trailers and co-authors

Trailers are Key: value lines at the very end of a message. You can add them with the --trailer option, and several platforms understand some of them: Co-authored-by: Name <email> credits a second author on GitHub, and Fixes: #42 can close an issue (see Issues and Projects).

Bash Adding trailers and temporary identities

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

(In this sandbox the GIT_AUTHOR_* variables override -c user.name, so the last commit still says Ada. The variables win over config files, which is a good thing to know when a commit mysteriously has the wrong author.) If no identity is configured at all, Git stops with Author identity unknown and tells you to set user.name and user.email; see Installing and Configuring Git.

Habits of people who write good history

  • Run git status and git diff --staged before every commit.
  • Commit early and often locally; then clean up before sharing (see Interactive Rebase).
  • Do not commit generated files, secrets or large binaries (see .gitignore).
  • Do not commit commented-out code "just in case". History is the "just in case".
  • Never put a password in a commit. Removing it later is painful, because it stays in history.
  • Keep tests and the code they test in the same commit.
  • Signing commits (git commit -S) proves who made them. It needs GPG or SSH keys, which the sandbox lacks; see Signing, Credentials and Security.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the parent line of a commit contain?

    Each commit stores the ID of its parent (two for a merge, none for the root commit). Following parent links is how Git walks through history.
  2. 2. You ran git commit -a, but a brand-new file was not included. Why?

    -a is a shortcut for git add -u. Untracked files must be added with git add first.
  3. 3. What happens to the hash when you run git commit --amend --no-edit?

    The hash covers the tree, parents, author, committer and message. The committer timestamp alone changes, so even a no-op amend normally creates a new hash (here it differs because the staged content changed).
  4. 4. Which subject line follows the usual conventions?

    Use the imperative mood, a specific description, no trailing period and one logical change per commit.
  5. 5. When is it safe to amend a commit?

    Amending creates a new commit with a new hash. If others already have the old one, your histories diverge.

Summary

  • A commit points to a full snapshot (tree), its parent(s), an author, a committer and a message; its hash is a checksum of all that, so it can never be edited, only replaced.
  • git commit -m takes the message inline (repeat -m for paragraphs), -a includes tracked changes, --allow-empty makes a marker commit, -F - reads the message from stdin.
  • git commit --amend fixes the last commit by creating a new one; only do it before sharing.
  • Atomic commits hold one logical change and keep the project working.
  • Write an imperative subject (about 50 characters), a blank line, and a body that explains why. Consider Conventional Commits if you automate releases.
  • Use trailers for co-authors, reviewers and issue references.

Next: Viewing History: log, show and Formatting