How to Commit Code in Git Using Command Line: A Step-by-Step Guide

Committing code is a fundamental part of using Git — it saves a snapshot of your project’s changes to the repository’s history. Whether you’re new to Git or just want a quick refresher, this guide shows you how to commit your code using the command line (CMD) on Windows or any terminal.


What Is a Git Commit?

A commit in Git represents a recorded state of your project. Each commit includes:

  • A snapshot of the changed files
  • A unique commit ID (hash)
  • A commit message describing the changes

Step 1: Open Command Line Interface

On Windows, open Command Prompt (CMD) or Git Bash. On macOS or Linux, open your preferred terminal.

Navigate to your project directory:

cd path/to/your/project

Step 2: Check Git Status

Before committing, check which files have been modified, added, or deleted:

git status

This helps you review your changes before committing.


Step 3: Stage Your Changes

Add the files you want to include in the commit to the staging area.

  • To add all changes:
git add .
  • To add specific files:
git add filename1 filename2

Step 4: Commit Your Changes

Once files are staged, create a commit with a clear, descriptive message:

git commit -m "Your commit message here"

Example:

git commit -m "Fix bug in user login validation"

Step 5: Verify Your Commit

To confirm your commit was successful, you can view the commit history with:

git log --oneline

This displays recent commits with their messages and IDs.


Summary of Commands

CommandPurpose
git statusCheck current changes
git add .Stage all changes
git add filenameStage specific files
git commit -m "msg"Commit staged changes with a message
git log --onelineView recent commits

Final Tips

  • Write meaningful commit messages to make your project history easier to understand.
  • Stage only the files you want to include in the commit.
  • Commit frequently to save your progress incrementally.
Sharing Is Caring:

Leave a Comment