Skip to main content

Git Commits

The building block of version control in Git is the commit. A commit represents a unit of work that includes changes to files, a commit message, and metadata like the author and timestamp.

The Staging Area

Git’s staging area is used to prepare changes for a commit. You can add or remove files from the staging area to control which changes are included in the next commit.

Stage Files

Add changes to the staging area using git add <pathspec>:

Unstage Files

Remove files from the staging area using git restore --staged <pathspec>:

Creating Commits

Use git commit -m <message> to create a new commit with the staged changes and the specified message.

Basic Commit

If you omit the -m option, Git will open the default text editor to enter the commit message.

Commit Without Running Git Hooks

If you want to skip the pre-commit and commit-msg hooks, use the --no-verify option:
Git hooks are usually set up to enforce coding standards, run tests, or perform other checks before allowing a commit. Use this option with caution.

Create an Empty Commit

Empty commits are sometimes useful when you want to mark a point in history without making any changes:
No changes will be included in the commit, but it will still be recorded in the repository history.

Viewing Commits

Check the current status of your working tree:
The -sb flag provides a more concise output, useful for quickly checking the status.

Commit Best Practices

Writing Good Commit Messages

A good commit message should:
  • Use the imperative mood (“Add feature” not “Added feature”)
  • Be concise but descriptive
  • Explain the “why” not just the “what”
  • Limit the first line to 50 characters
  • Provide additional context in the body if needed

Commit Frequency

  • Commit early and often
  • Each commit should represent a logical unit of work
  • Avoid mixing unrelated changes in a single commit
  • Commit working code, not broken code

Common Commit Workflows

Standard Workflow

Selective Staging

Review Before Committing

Commit Tips

  • Use git status frequently to understand the current state
  • Review changes with git diff before staging
  • Use git diff --staged to review what will be committed
  • Keep commits focused and atomic
  • Don’t commit sensitive information (API keys, passwords, etc.)
  • Test your changes before committing
  • Use meaningful commit messages that future you will understand