Git Basics
Git Basics Explained
Git is a distributed version control system that tracks changes in files, enabling collaboration and history management for projects. Here’s a concise guide to learn Git.
Key Concepts
- Repository (Repo):
A project folder tracked by Git. Contains all files and their history. - Commit:
A snapshot of changes at a point in time (with a unique ID and message). - Branch:
An independent line of development (default:main
ormaster
). - Remote:
A cloud-hosted repo (e.g., GitHub, GitLab and even in a local folder) for team collaboration. - Staging Area:
A “preview” space where changes are prepared before committing.
Essential Commands
Command | Description |
---|---|
git init | Creates a new repo in the current folder. |
git clone <url> | Downloads a remote repo to your machine. |
git add <file> | Stages changes for commit. |
git add . | Stages all files in the current folder. |
git commit -m "Message" | Saves staged changes to history. |
git status | Shows unstaged/staged changes. |
git log | Displays commit history. |
Branching & Merging
- Create branch:
git checkout -b new-branch-name # Create and switch to a new branch
- Switch branch:
git switch branch-name # Switch to target branch git checkout branch-name # Switch to target branch
- Merge branches:
git merge branch-name # Merge <branch-name> changes into the current branch
- Resolve conflicts:
Manually edit conflicted files, thengit add
andgit commit
.
Syncing with Remotes
Command | Purpose |
---|---|
git remote add origin <url> | Links local repo to a remote. |
git push -u origin main | Uploads commits to remote (set upstream). |
git pull | Fetches remote changes and merges locally. |
git fetch | Downloads remote changes without merging. |
Undoing Changes
- Unstage a file:
git reset HEAD <file>
- Discard unstaged changes:
git checkout -- <file>
- Revert a commit:
git revert <commit-id> # Creates a new commit undoing changes
Best Practices
- Commit often: Small, logical changes with clear messages.
- Branch early: Use branches for features/fixes.
- Pull before push: Avoid merge conflicts.
- Use
.gitignore
: Exclude files (e.g., logs, binaries). - Review changes:
git diff # Unstaged changes git diff --staged # Staged changes
Example Workflow
# Clone a repo
git clone https://github.com/user/project.git
# Create a new branch <dev> adn switch into it
git checkout -b dev
# Make changes, then stage & commit
git add index.html
git commit -m "Up date index"
# Push to remote branch
# (Create a new remote branch if there's no dev branch in remote repo.)
git push origin dev:dev
Git’s power lies in its flexibility—start with these basics, then explore advanced features as needed!