Git Commits – Save, Track and Manage Code Changes
Imagine you are developing an employee management application. You have completed the employee registration feature, fixed a validation issue, and updated the database integration. A few hours later, another change introduces a problem. You now need to identify exactly what changed and return to the last working version.
Without a reliable way to record changes, tracking this work becomes difficult. You may end up copying folders, renaming files, or trying to remember which version was working.
This is where Git commits become important. A commit records a snapshot of your project at a particular point in time. It gives your team a meaningful history of how the codebase has evolved.
- What a Git commit is and why developers create commits.
- How the working directory, staging area and repository work together.
- How to create, inspect and manage commits using Git commands.
- How to write meaningful commit messages.
- How to correct mistakes and follow safe commit practices.
1. What Is a Git Commit?
A Git commit is a saved snapshot of the staged changes in a Git repository. It records which project content was committed, who created the commit, when it was created, its commit message, and its relationship to earlier commits.
Think of a commit as a checkpoint in your application's development history. You can inspect earlier checkpoints, compare changes between them, and use them to understand how the project reached its current state.
Why do developers create commits?
- Track changes: Understand what changed and when.
- Maintain history: Keep a sequence of meaningful development checkpoints.
- Collaborate: Share recorded work with other developers through a remote repository.
- Investigate defects: Identify which commit introduced a problem.
- Review code: Inspect the changes included in a particular commit.
- Recover work: Restore or reuse earlier project states when needed.
git push to publish your local commits to a remote repository.2. Understanding the Three Main Areas in Git
Before creating a commit, you should understand how Git manages changes. Git uses three important areas during the normal commit workflow.
2.1 Working directory
The working directory is the project folder where you create, edit, and delete files. When you modify an existing file or add a new file, the change first exists in your working directory.
2.2 Staging area
The staging area is where you prepare the exact changes that should become part of your next commit. The command git add moves selected changes into this area.
You do not have to commit every modified file together. You can stage only the files related to one logical task.
2.3 Local repository
The local repository stores Git's commit history and related repository data. When you run git commit, Git creates a new commit using the staged content and records it in the local repository.
The normal Git workflow: edit files, stage selected changes, and create a commit in the local repository.
How the three areas differ
| Area | Purpose | Common command |
|---|---|---|
| Working directory | Contains the files you are currently editing. | git status |
| Staging area | Holds selected changes for the next commit. | git add |
| Local repository | Stores commits and project history. | git commit |
3. How a Git Commit Works Internally
Git does not simply save a duplicate copy of your entire project every time you commit. It stores repository content using objects and connects those objects through commit history.
A commit object contains important metadata, including:
- Tree reference: Identifies the directory snapshot associated with the commit.
- Parent reference: Identifies the previous commit or commits. A normal commit usually has one parent. A merge commit can have multiple parents, while a root commit has none.
- Author: The person credited with originally creating the change.
- Committer: The person who created this particular commit object.
- Timestamp: Records the author and committer dates.
- Commit message: Explains the purpose of the change.
Git also stores file content in objects called blobs and directory information in tree objects. Git identifies these objects using content-based hashes. Modern Git repositories use SHA-1 or, when configured, SHA-256 object formats.
A simplified view of commit history. Each commit points to a project tree and links to its parent commit.
4. Configure Your Git Identity
Git records author and committer information in commits. Before creating commits, configure the name and email address you want Git to use.
To configure your identity globally for repositories on your computer:
Example 1: Configure Git username and email
git config --global user.name "Chakrapani Upadhyaya"
git config --global user.email "chakrapani@example.com"
Check the configured values:
Example 2: Verify Git identity
git config --global user.name
git config --global user.email
Chakrapani Upadhyaya chakrapani@example.com
You can also configure identity for one repository by running the commands without --global from inside that repository.
5. Create Your First Git Commit
Let's create a small employee management project and record its first commit. The example assumes Git is installed and you are working in a terminal.
Step 1: Create a project folder
Example 3: Create the project directory
mkdir EmployeeManagement
cd EmployeeManagement
Step 2: Initialize a Git repository
Run git init to create a new Git repository in the current directory.
Example 4: Initialize Git
git init
Initialized empty Git repository in EmployeeManagement/.git/
Git creates a hidden .git directory. This directory stores the repository's configuration, objects, references and other Git metadata.
Step 3: Create a sample file
Create a file named README.md with the following content:
Example 5: README.md
# Employee Management
A simple application to manage employee information.
## Features
- Add employees
- View employee details
- Update employee information
- Manage employee status
Step 4: Check the repository status
Run git status to understand which files are untracked, modified or staged.
Example 6: Check Git status
git status
On branch main No commits yet Untracked files: (use "git add <file>..." to include in what will be committed) README.md nothing added to commit but untracked files present (use "git add" to track)
The file exists in your project folder, but Git has not started tracking it yet.
Step 5: Stage the file
Use git add to place the file in the staging area.
Example 7: Stage README.md
git add README.md
Check the status again:
Example 8: Verify the staged file
git status
On branch main No commits yet Changes to be committed: (use "git rm --cached <file>..." to unstage) new file: README.md
The file is now staged and ready to be included in a commit.
Step 6: Create the commit
Run git commit with a meaningful message.
Example 9: Create the first commit
git commit -m "Add employee management project README"
[main (root-commit) a1b2c3d] Add employee management project README 1 file changed, 10 insertions(+) create mode 100644 README.md
Your first commit is now stored in the local repository. The displayed short hash is an abbreviated identifier for that commit.
6. Understand the Most Important Commit Commands
These commands help you stage changes, create commits, inspect history and understand what will be included in your next commit.
6.1 Stage one file
git add Employee.cs
Stages the changes in Employee.cs.
6.2 Stage multiple files
git add Employee.cs EmployeeService.cs
Stages the selected files together.
6.3 Stage all changes in the current directory
git add .
Stages new, modified and deleted files under the current directory, subject to ignore rules.
git add .: It can stage files you did not intend to include. Review the staged changes with git status and git diff --cached before committing.6.4 Create a commit with a message
git commit -m "Add employee registration endpoint"
Creates a commit using the current staging area and the supplied message.
6.5 View commit history
git log
Displays commit history, including commit hashes, authors, dates and messages.
6.6 View compact commit history
git log --oneline
Displays one concise line per commit.
6.7 Inspect a particular commit
git show <commit-hash>
Displays the commit metadata and its patch. Replace <commit-hash> with the actual commit identifier.
6.8 Compare staged changes
git diff --cached
Shows the differences between the staging area and the current HEAD commit. Before the first commit, it compares against the empty initial state.
6.9 Compare unstaged changes
git diff
Shows changes in tracked files that have not yet been staged. It does not show the content of untracked files.
| Command | Purpose |
|---|---|
git status |
Shows the current working tree and staging status. |
git add |
Stages selected changes. |
git commit |
Creates a commit from staged changes. |
git log |
Displays commit history. |
git show |
Inspects a commit and its changes. |
git diff |
Shows unstaged differences in tracked files. |
git diff --cached |
Shows staged differences. |
git restore --staged |
Removes changes from staging without discarding the working copy. |
7. Understand Git Commit Messages
A commit message explains why a change was made. Good messages make project history easier to understand during code reviews, debugging and maintenance.
Examples of unclear commit messages
git commit -m "Changes"
git commit -m "Updated code"
git commit -m "Fix"
git commit -m "Final update"
These messages do not explain what the developer actually changed.
Examples of meaningful commit messages
git commit -m "Add employee registration endpoint"
git commit -m "Fix duplicate employee email validation"
git commit -m "Update loan application status mapping"
git commit -m "Add pagination to employee search API"
Use Conventional Commits when your team follows that convention
Conventional Commits is a commonly used format that gives commit messages a predictable structure:
Commit message format
<type>[optional scope]: <description>
Common types include:
| Type | Meaning | Example |
|---|---|---|
| feat | Introduces a feature. | feat(employee): add registration API |
| fix | Fixes a defect. | fix(employee): prevent duplicate email |
| docs | Changes documentation. | docs: update setup instructions |
| refactor | Changes code structure without changing intended behaviour. | refactor: extract employee validation |
| test | Adds or updates tests. | test: cover employee registration |
| chore | Performs maintenance work. | chore: update development tooling |
For example:
git commit -m "feat(employee): add registration API"
8. Create Meaningful and Atomic Commits
A good commit should represent one logical unit of work. This practice is often called an atomic commit.
Consider an employee management application where you are working on three separate tasks:
- Add employee registration.
- Fix employee email validation.
- Update application documentation.
Instead of combining unrelated changes into one large commit, create separate commits where practical.
Example 10: Separate commits for separate tasks
git add EmployeeController.cs
git commit -m "feat(employee): add registration endpoint"
git add EmployeeValidator.cs
git commit -m "fix(employee): validate duplicate email"
git add README.md
git commit -m "docs: update employee setup guide"
This makes it easier to review each change, identify defects and revert a specific logical change when necessary.
Why atomic commits are useful
- Code reviews become easier because each commit has a clear purpose.
- Bug investigation becomes more focused.
- Changes can be reverted more selectively.
- Team members can understand the history without reading unrelated changes.
- Automated tools can use commit messages and history more effectively.
9. Amend the Previous Commit
Sometimes you create a commit and immediately realise that you forgot to include a small change or used an incorrect commit message. Git provides git commit --amend to replace the latest commit with an updated one.
Example: Update the previous commit message
git commit --amend -m "feat(employee): add employee registration"
Example: Include an additional staged file
git add EmployeeValidator.cs
git commit --amend --no-edit
The --no-edit option keeps the previous commit message while replacing the latest commit with one that includes the newly staged changes.
10. Undo or Correct Commit-Related Changes
Git provides several commands to correct mistakes. They are not interchangeable. The right command depends on whether the changes are staged, unstaged, committed locally or already shared.
10.1 Unstage a file without deleting its changes
If you staged a file by mistake, use:
git restore --staged Employee.cs
This removes the file's staged changes from the staging area while keeping the changes in your working directory.
10.2 Discard unstaged changes in a tracked file
git restore Employee.cs
This restores the file's working-directory content from the index. Any unstaged changes in that file are discarded.
git restore Employee.cs can permanently discard uncommitted changes in that file. Inspect the file and make a backup if you are unsure.10.3 Revert a commit safely
If a commit has already been pushed or shared, git revert is usually the safer way to undo its effect.
git revert <commit-hash>
Git creates a new commit that reverses the changes introduced by the selected commit. The existing commit history remains intact.
10.4 Reset the current branch to an earlier commit
git reset moves the current branch reference to another commit. Its effect on the staging area and working directory depends on the selected mode.
git reset --soft HEAD~1
git reset --mixed HEAD~1
git reset --hard HEAD~1
| Mode | Branch / HEAD | Staging area | Working directory |
|---|---|---|---|
--soft |
Moves to target commit. | Keeps changes staged. | Keeps changes. |
--mixed |
Moves to target commit. | Resets staging area. | Keeps changes. |
--hard |
Moves to target commit. | Resets staging area. | Resets tracked files to target state. |
git reset --hard with extreme care. It discards tracked working-directory and staging changes that are not present in the target commit. It does not normally remove untracked files. Do not run it until you understand exactly which changes will be lost.Revert vs reset: which should you use?
| Situation | Recommended command | Reason |
|---|---|---|
| Remove a file from staging but keep its edits. | git restore --staged |
Preserves working-directory changes. |
| Discard unstaged edits in a tracked file. | git restore |
Restores the file from the index. |
| Undo a commit that has been shared. | git revert |
Adds a new commit that reverses the selected change. |
| Remove a recent local commit but keep changes staged. | git reset --soft |
Moves the branch while preserving staged content. |
| Move a local branch and discard tracked changes. | git reset --hard |
Resets the branch, index and tracked working files. |
11. Inspect and Navigate Commit History
Commit history helps developers understand the evolution of a project. Git provides several ways to inspect it.
View all commits
git log
View compact history
git log --oneline
View history with a branch graph
git log --oneline --graph --decorate --all
This command is particularly useful when multiple branches have different commit histories.
View the latest commit
git show HEAD
View the files changed in a commit
git show --stat <commit-hash>
Find commits that changed a particular file
git log -- EmployeeService.cs
These commands are useful during code reviews, production investigations and debugging sessions.
12. Commit and Push Are Different Operations
This is one of the most common misunderstandings for developers who are new to Git and GitHub.
A commit records changes in your local repository. A push sends local commits to a remote repository, such as a GitHub repository.
A commit stays local until you push it to the remote repository.
For example, after creating a commit, you can publish it with:
git push origin main
Here, origin is the remote name and main is the branch being pushed.
13. Common Git Commit Mistakes
1. Committing without checking the staged changes
Problem: Unrelated files or unfinished work may be included in the commit.
Better approach: Run git status and git diff --cached before committing.
2. Creating one very large commit
Problem: It becomes difficult to review, debug or revert individual changes.
Better approach: Group related changes into small, logical commits.
3. Using unclear commit messages
Problem: Other developers cannot understand the purpose of the change from the history.
Better approach: Explain the actual change using a short, specific message.
4. Assuming commit automatically updates GitHub
Problem: Your changes remain in the local repository and are not visible to collaborators.
Better approach: Push the required commits after creating and reviewing them.
5. Committing sensitive information
Problem: Passwords, access tokens, private keys and connection strings can become part of repository history.
Better approach: Use environment variables or a secure secret-management system. Add appropriate files to .gitignore before staging them.
6. Rewriting shared commit history without coordination
Problem: Amending or resetting commits that teammates already use can create synchronization problems.
Better approach: Prefer git revert for undoing changes in shared history, unless your team has a specific history-rewriting workflow.
14. Best Practices for Professional Git Commits
- Create commits around one logical change.
- Write clear messages that describe the purpose of the change.
- Review staged changes before committing.
- Run relevant tests before creating a commit.
- Avoid committing generated files unless the project requires them.
- Never commit passwords, tokens, private keys or sensitive configuration.
- Follow your team's commit message convention.
- Do not amend or rewrite shared commits without agreement.
- Use branches and pull requests for collaborative development.
- Push completed commits to the appropriate remote branch.
15. Real-World Team Workflow
Consider a team building a banking application. One developer is responsible for adding a loan application validation feature. The team uses Git branches and GitHub pull requests to review changes before merging them into the main branch.
A typical workflow looks like this:
A simplified team workflow from feature development to pull request review.
Example commands for the developer:
Example 11: Feature branch and commit workflow
# Create and switch to a feature branch
git switch -c feature/loan-validation
# Check the current changes
git status
# Stage related files
git add LoanApplicationValidator.cs
# Create a meaningful commit
git commit -m "feat(loan): validate loan application details"
# Publish the feature branch
git push -u origin feature/loan-validation
After pushing, the developer opens a pull request on GitHub. Teammates review the code, request changes if necessary, and approve the pull request when the required checks are satisfied.
16. Interview Questions and Answers
A Git commit is a snapshot of the staged project state recorded in the local repository. It includes metadata such as the author, timestamp, commit message and parent reference.
git add stages selected changes. git commit records the staged changes as a new commit in the local repository.
No. A commit is stored locally. Use git push to publish local commits to a remote repository.
The staging area is the intermediate area where developers prepare the exact changes for the next commit. It allows developers to commit selected changes instead of every modification in the working directory.
git diff shows unstaged differences in tracked files. git diff --cached shows the differences that are staged and ready for the next commit.
It creates a replacement for the latest commit, using the current staged changes and optionally an updated commit message. The replacement commit has a different ID.
git revert creates a new commit that reverses an earlier commit. git reset moves the current branch reference to another commit and can also change the staging area and working directory depending on the mode.
A commit contains a reference to a tree snapshot, parent commit reference or references, author and committer metadata, timestamps and a commit message.
Yes. A commit message is not required to be unique. Git identifies commits using their object IDs, which are based on the commit object's content and metadata.
An atomic commit contains one logical unit of work. It is easier to review, test, understand and revert than a commit that combines unrelated changes.
Rewriting shared history changes commit identities and can cause other developers' local branches to diverge from the updated remote history. Teams generally prefer new corrective commits, such as those created by git revert, for shared changes.
Small, descriptive commits make it easier to review changes, trace defects, identify when behaviour changed, understand the reason behind modifications and selectively revert a logical unit of work.
17. Hands-On Practice
Now practise the complete commit workflow using a small project.
Exercise 1: Create your first commit
- Create a folder named
GitCommitPractice. - Initialize a Git repository.
- Create a
README.mdfile. - Stage the file and create your first commit.
Expected result: Your repository should contain one commit in its history.
Exercise 2: Create separate commits
- Create
Employee.cs. - Create
EmployeeService.cs. - Stage and commit each logical change separately.
- Review the history using
git log --oneline.
Expected result: You should see separate commits with meaningful messages.
Exercise 3: Correct a commit message
- Create a commit with an unclear message.
- Use
git commit --amend -mto replace the latest commit message. - Inspect the updated commit using
git show HEAD.
Expected result: The latest commit should have the updated message and a replacement commit ID.
Exercise 4: Practise safe undo operations
- Modify a tracked file.
- Stage the modification.
- Unstage it using
git restore --staged. - Inspect the working directory using
git status.
Expected result: The file should no longer be staged, but its working-directory changes should remain.
Exercise 5: Inspect your commit history
- Create at least three meaningful commits.
- Run
git log --oneline. - Inspect one commit using
git show. - Compare staged and unstaged changes using the appropriate
git diffcommands.
Expected result: You should be able to explain what each commit changed and how it relates to the current project state.
18. Conclusion
Git commits are one of the most important building blocks of version control. They allow developers to record meaningful project snapshots, understand code history, collaborate with teammates and investigate changes over time.
The most important workflow to remember is:
git status
git add <file-name>
git diff --cached
git commit -m "Describe the change"
git log --oneline
Do not treat commits as a final step performed only when development is complete. Create small, meaningful commits throughout development. Review what you are staging, write clear messages and understand the difference between local commits and remote pushes.
Once you are comfortable with commits, you are ready to understand how Git branches help developers work on multiple features independently.
19. Official Documentation and Further Learning
- Git Documentation – git commit
- Git Documentation – git add
- Git Documentation – git log
- Git Documentation – git restore
- Git Documentation – git reset
- Git Documentation – git revert
- Conventional Commits Specification
- GitHub Docs – About Git