Git commit is a core Git command used to save changes from the staging area into the repository’s history. Each commit acts as a snapshot of your project at a particular point in time, allowing you to track, review, and revert changes if needed. Think of it as saving your work in Git.
- When we run
git commit, Git takes whatever is currently staged and writes that snapshot into the repository, along with metadata (author, timestamp, parent commit, message). - The working directory and staging area remain; we can continue making further changes.
How to Use Git commit
1. Commit with a Message
git commit -m "Initial commit"
- Saves staged changes with the provided message.
- Messages should be concise but descriptive.
2. Commit All Changes at Once
git commit -a -m "Update all tracked files"
- Automatically stages modified and deleted tracked files before committing.
- Note: Does not include untracked files—you still need
git add for those.
3. Amend Last Commit
git commit --amend -m "Updated commit message"
- Modify the last commit’s message or add new staged changes.
- Useful for correcting mistakes in the most recent commit.
4. Commit Interactively
git commit -p
- Allows you to commit changes hunk by hunk, giving fine-grained control over commits.
git commitCommon Options with git commit
| Option | Description |
|---|
-m | Add a commit message inline |
-a | Automatically stage modified and deleted tracked files |
--amend | Modify the last commit |
-p | Commit interactively by hunk |
--dry-run | Show what would be committed without actually committing |
working with Git Commit
1. Understanding Commits and HEAD
- Each commit is a node; HEAD points to the latest commit.
- Commits form a right-to-left singly linked list: new commits point to previous ones, and HEAD moves to the newest commit.
2. Git Commit Flags
Git provides several flags to customize commits:
git commit -m "commit message": Creates a commit with the given commit message.git commit -a: Automatically stages all tracked files that have been modified and commits them.git commit -am "commit message": Combines the above two; stages all tracked files and commits with a message in a single command.
3. Handling Modifications After a Commit
- Modify files -
git add - git commit. - View changes:
git show. - View history:
git log.
Shows a running record of all commits.
4. Amending a Commit
To fix the last commit without adding a new history:
git commit --amend -m "new message"