Git is the most widely-used distributed version control system for tracking changes in source code during software development. It helps developers collaborate, manage changes, and maintain code quality over time.
Think of Git as a time machine for your codebase.
A Git repository (or repo) is a project directory with a special hidden folder called .git
. This folder stores metadata, commit history, branches, and more.
A Git repo = your project + its full timeline of changes.
Git tracks your files through three distinct states:
State | Description |
---|---|
Modified | Youโve made changes to a file, but havenโt staged it yet. |
Staged | Youโve marked changes to be included in the next commit. |
Committed | Changes are safely stored in the Git database as a snapshot of your work. |
Branches allow parallel development. You can work on features or bug fixes in isolated branches, then merge them into main
when ready.
Pro Tip: Always create a new branch for a feature or fix. Avoid committing directly to
main
.
Merging integrates changes from one branch into another. For example:
git checkout main
git merge feature-branch
After merging, the
main
branch will include all changes fromfeature-branch
.
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global core.editor "code --wait"
Line-ending configuration:
macOS/Linux:
git config --global core.autocrlf input
Windows:
git config --global core.autocrlf true
View/edit global config:
git config --global -e
Initialize a Git repository:
git init
Check repo status:
git status
Stage a specific file:
git add <file-name>
Stage everything:
git add .
Unstage a file:
git reset <file-name>
Commit changes:
git commit -m "Describe your change clearly"
Tip: Use short, meaningful commit messages like
"Fix login redirect bug"
.
Save work-in-progress:
git stash
Restore stashed changes:
git stash apply
Create a new branch:
git branch <branch-name>
Switch to a branch:
git checkout <branch-name>
Create and switch in one command:
git checkout -b <branch-name>
Revert a specific commit:
git revert <commit-hash>
Reset changes in working directory:
git reset
Be cautious with
reset
โit alters history. Userevert
in collaborative environments.
View commit history:
git log
Quick, one-line log:
git log --oneline
Compare file changes:
git diff
Move a branch onto another base:
git rebase <branch-name>
Use rebase for a cleaner history, but only on your own branchesโnever rebase shared branches unless youโre sure.
Action | Command |
---|---|
Initialize repository | git init |
Stage changes | git add . or git add <file> |
Commit changes | git commit -m "message" |
Check status | git status |
View history | git log , git log --oneline |
Create/switch branch | git checkout -b <branch> |
Merge branches | git merge <branch> |
Stash work | git stash / git stash apply |
Undo commit (safe) | git revert <hash> |
Compare changes | git diff |