Git Tutorial: Complete Guide from Basic to Advanced with Examples (2025)
Git Tutorial: Complete Guide from Basic to Advanced with Examples (2025)
If you're a developer, you've probably heard about Git - the version control system that has become essential for modern software development. Whether you're just starting your programming journey or looking to master advanced Git techniques, this comprehensive guide will take you from Git basics to advanced concepts with practical examples you can use right away.
What is Git?
Git is a distributed version control system that helps developers track changes in their code, collaborate with team members, and manage different versions of their projects. Created by Linus Torvalds in 2005, Git has become the most popular version control system in the world, used by millions of developers and companies like Google, Microsoft, Facebook, and Netflix.
Think of Git as a time machine for your code. It allows you to:
- Save snapshots of your project at different points in time
- Go back to previous versions if something breaks
- Work on new features without affecting the main code
- Collaborate with multiple developers simultaneously
- Keep a complete history of who changed what and when
Unlike older version control systems, Git is distributed, meaning every developer has a complete copy of the project history on their local machine. This makes Git fast, reliable, and perfect for both small personal projects and large enterprise applications. Learn more from the official Git documentation.
Why Git is Important: Benefits and Use Cases
Git has transformed how developers work, and understanding it is crucial for your programming career. Here are the key benefits:
Professional Development Benefits:
- Industry Standard: 95% of companies use Git for version control
- Career Essential: Git knowledge is required for almost every developer job
- Open Source Contribution: Contributing to open source projects requires Git skills
- Portfolio Building: Showcase your projects on GitHub, GitLab, or Bitbucket
Technical Advantages:
- Backup and Recovery: Never lose your code again - Git maintains complete history
- Branching and Merging: Work on multiple features simultaneously without conflicts
- Collaboration: Multiple developers can work on the same project efficiently
- Code Review: Track who made what changes and review code before merging
- Experimentation: Try new ideas without risking your stable code
- Offline Work: Most Git operations work offline, perfect for remote work
Real-World Use Cases:
- Web development teams managing application code
- Data scientists versioning machine learning models and datasets
- Writers and content creators tracking document changes
- DevOps engineers managing infrastructure as code
- Mobile app developers coordinating iOS and Android codebases
Whether you're working on backend projects or learning Python programming, Git is an essential tool.
How Git Works: Understanding the Core Concepts
Git works by taking snapshots of your project at different points in time. Understanding how Git works will help you use it more effectively.
The Three States of Git:
Git has three main states that your files can be in:
- Modified: You've changed the file but haven't saved it to Git yet
- Staged: You've marked the modified file to be included in your next snapshot
- Committed: The file is safely stored in your Git database
The Git Workflow:
Working Directory → Staging Area → Local Repository → Remote Repository
(modify) (stage) (commit) (push)
Here's how it works step-by-step:
- Working Directory: This is where you modify your files - your actual project folder
- Staging Area (Index): A temporary holding area where you prepare files for commit
- Local Repository (.git folder): Where Git stores all committed snapshots on your computer
- Remote Repository (GitHub/GitLab): A cloud-based copy that enables collaboration
Example Workflow:
# 1. Modify files in your working directory
echo "Hello Git!" > welcome.txt
# 2. Stage the changes (add to staging area)
git add welcome.txt
# 3. Commit the changes (save to local repository)
git commit -m "Add welcome message"
# 4. Push to remote repository (share with team)
git push origin main
The .git Folder:
When you initialize Git in a project, it creates a hidden .git folder that contains:
- All commits and snapshots
- Branch information
- Configuration settings
- Object database
This is why Git is so fast - everything is stored locally on your machine!
Key Features of Git
- Distributed Architecture: Every developer has a complete copy of the repository
- Branching and Merging: Create isolated environments for features and experiments
- Speed: Most operations are lightning-fast because they're local
- Data Integrity: Git uses SHA-1 hashing to ensure your data is never corrupted
- Staging Area: Review and organize changes before committing
- Free and Open Source: Completely free to use with active community support
- Platform Independent: Works on Windows, Mac, Linux, and more
- Lightweight: Minimal storage overhead with efficient compression
- Non-linear Development: Support for multiple parallel workflows
- Tracking Changes: Complete audit trail of who changed what and when
Git Installation and Setup: Getting Started
Before you can use Git, you need to install it and configure your identity. Here's how to get started on different operating systems.
Installing Git:
On Windows:
# Download Git from https://git-scm.com/download/win
# Run the installer and follow the setup wizard
# Verify installation
git --version
On Mac:
# Using Homebrew
brew install git
# Or download from https://git-scm.com/download/mac
# Verify installation
git --version
On Linux (Ubuntu/Debian):
sudo apt-get update
sudo apt-get install git
# Verify installation
git --version
Initial Git Configuration:
After installing Git, configure your identity. This information will be included in every commit you make:
# Set your name
git config --global user.name "Your Name"
# Set your email
git config --global user.email "your.email@example.com"
# Set default branch name to 'main'
git config --global init.defaultBranch main
# Set default text editor
git config --global core.editor "code --wait" # For VS Code
# View your configuration
git config --list
# View specific config
git config user.name
Useful Configuration Options:
# Enable colored output
git config --global color.ui auto
# Set up aliases for common commands
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
# Configure line ending handling
git config --global core.autocrlf true # Windows
git config --global core.autocrlf input # Mac/Linux
Git Basic Commands with Examples
Let's dive into the essential Git commands every developer needs to know. These commands form the foundation of your Git workflow.
1. Creating a Repository:
# Create a new directory for your project
mkdir my-project
cd my-project
# Initialize Git in the directory
git init
# You'll see: Initialized empty Git repository in /path/to/my-project/.git/
2. Checking Repository Status:
# See what's changed in your working directory
git status
# Short status format
git status -s
3. Adding Files to Staging Area:
# Add a specific file
git add index.html
# Add multiple files
git add index.html style.css script.js
# Add all files in current directory
git add .
# Add all files in the repository
git add -A
# Add files with specific pattern
git add *.js
4. Committing Changes:
# Commit staged changes with a message
git commit -m "Add homepage layout"
# Commit with detailed message (opens editor)
git commit
# Add and commit in one step (only for tracked files)
git commit -am "Update header styles"
5. Viewing Commit History:
# Show all commits
git log
# Show last 5 commits
git log -5
# Show commits in one line
git log --oneline
# Show commits with graph
git log --graph --oneline --all
# Show commits by author
git log --author="Your Name"
# Show commits with file changes
git log --stat
Practical Example - Your First Git Workflow:
# 1. Create a new project
mkdir blog-website
cd blog-website
git init
# 2. Create some files
echo "<h1>My Blog</h1>" > index.html
echo "body { margin: 0; }" > style.css
# 3. Check status
git status
# Output: Shows untracked files
# 4. Add files to staging
git add .
# 5. Commit your work
git commit -m "Initial commit: Add homepage"
# 6. Make more changes
echo "<p>Welcome to my blog!</p>" >> index.html
# 7. See what changed
git diff
# 8. Stage and commit
git add index.html
git commit -m "Add welcome message to homepage"
# 9. View your history
git log --oneline
Working with Remote Repositories (GitHub, GitLab, Bitbucket)
Remote repositories allow you to collaborate with other developers and backup your code. Let's learn how to work with platforms like GitHub.
Connecting to a Remote Repository:
# Add a remote repository
git remote add origin https://github.com/yourusername/your-repo.git
# View remote repositories
git remote -v
# Push your code to remote
git push -u origin main
# The -u flag sets upstream tracking
Cloning a Repository:
# Clone a public repository
git clone https://github.com/username/repository.git
# Clone into a specific directory
git clone https://github.com/username/repository.git my-folder
# Clone a specific branch
git clone -b develop https://github.com/username/repository.git
Fetching and Pulling Updates:
# Fetch updates from remote (doesn't merge)
git fetch origin
# Pull updates (fetch + merge)
git pull origin main
# Pull with rebase instead of merge
git pull --rebase origin main
Pushing Changes:
# Push to remote repository
git push origin main
# Push a new branch
git push -u origin feature-branch
# Force push (use carefully!)
git push --force origin main
# Delete remote branch
git push origin --delete old-branch
Real-world Example - Contributing to Open Source:
# 1. Fork the repository on GitHub
# 2. Clone your fork
git clone https://github.com/yourusername/project.git
cd project
# 3. Add original repo as upstream
git remote add upstream https://github.com/original-owner/project.git
# 4. Create a feature branch
git checkout -b fix-bug
# 5. Make your changes
# ... edit files ...
# 6. Commit your changes
git add .
git commit -m "Fix: Resolve issue with login validation"
# 7. Push to your fork
git push origin fix-bug
# 8. Create Pull Request on GitHub
Git Branching and Merging Strategies
Branching is one of Git's most powerful features. It allows you to work on different features simultaneously without affecting the main codebase. Learn more about branching strategies from Atlassian's Git tutorials.
Working with Branches:
# List all branches
git branch
# Create a new branch
git branch feature-login
# Switch to a branch
git checkout feature-login
# Create and switch in one command
git checkout -b feature-signup
# Switch branches (newer syntax)
git switch feature-login
# Create and switch (newer syntax)
git switch -c feature-payment
Merging Branches:
# Merge feature branch into main
git checkout main
git merge feature-login
# Merge with commit message
git merge feature-login -m "Merge login feature"
# Abort a merge
git merge --abort
Resolving Merge Conflicts:
When Git can't automatically merge changes, you'll need to resolve conflicts manually:
# 1. Attempt to merge
git merge feature-branch
# 2. Git reports conflicts
# CONFLICT (content): Merge conflict in index.html
# 3. Check conflict status
git status
# 4. Open conflicted file
# You'll see markers like:
# <<<<<<< HEAD
# Your current branch code
# =======
# Feature branch code
# >>>>>>> feature-branch
# 5. Edit file to resolve conflict
# Remove conflict markers and keep desired code
# 6. Stage resolved file
git add index.html
# 7. Complete the merge
git commit -m "Merge feature-branch and resolve conflicts"
Branch Management:
# Delete local branch
git branch -d feature-login
# Force delete unmerged branch
git branch -D feature-experimental
# Rename branch
git branch -m old-name new-name
# List remote branches
git branch -r
# List all branches (local and remote)
git branch -a
# Show merged branches
git branch --merged
# Show unmerged branches
git branch --no-merged
Popular Branching Strategies:
1. GitFlow:
# Main branches:
# - main (production)
# - develop (integration)
# Supporting branches:
# - feature/feature-name
# - release/version
# - hotfix/fix-name
# Example workflow
git checkout develop
git checkout -b feature/user-auth
# ... work on feature ...
git checkout develop
git merge feature/user-auth
2. GitHub Flow:
# Simpler strategy:
# - main branch is always deployable
# - Create feature branches from main
# - Open PR when ready
# - Merge after review
git checkout -b feature-comments
# ... make changes ...
git push origin feature-comments
# Create PR on GitHub
# After approval, merge to main
Undoing Changes: Reset, Revert, and Restore
Everyone makes mistakes. Git provides several ways to undo changes:
Git Reset:
# Unstage files (keep changes)
git reset HEAD file.txt
# Reset to previous commit (keep changes)
git reset --soft HEAD~1
# Reset to previous commit (unstage changes)
git reset --mixed HEAD~1
# Reset to previous commit (discard changes) - DANGEROUS!
git reset --hard HEAD~1
# Reset to specific commit
git reset --hard abc123
Git Revert:
Revert creates a new commit that undoes previous changes (safer for shared branches):
# Revert last commit
git revert HEAD
# Revert specific commit
git revert abc123
# Revert without creating commit
git revert -n HEAD
Git Restore (newer command):
# Discard changes in working directory
git restore file.txt
# Restore file from specific commit
git restore --source HEAD~2 file.txt
# Unstage file
git restore --staged file.txt
Git Checkout for Files:
# Discard changes to specific file
git checkout -- file.txt
# Restore file from specific commit
git checkout abc123 -- file.txt
Git Stash: Temporarily Save Your Work
Stash is useful when you need to switch branches but aren't ready to commit:
# Save current changes
git stash
# Save with message
git stash save "WIP: working on login form"
# List all stashes
git stash list
# Apply most recent stash
git stash apply
# Apply and remove stash
git stash pop
# Apply specific stash
git stash apply stash@{2}
# Show stash contents
git stash show -p
# Create branch from stash
git stash branch feature-from-stash
# Clear all stashes
git stash clear
Practical Stash Example:
# Working on feature
git checkout feature-payment
# ... editing files ...
# Urgent bug reported on main!
git stash save "WIP: payment integration"
git checkout main
git checkout -b hotfix-critical
# Fix the bug
# ... fix code ...
git add .
git commit -m "Fix: critical security issue"
git checkout main
git merge hotfix-critical
# Return to feature work
git checkout feature-payment
git stash pop
# Continue where you left off!
Advanced Git: Rebase, Cherry-Pick, and More
For advanced workflows, especially when working with modern languages like Rust, these commands are invaluable:
Git Rebase:
Rebase rewrites history to create a linear timeline:
# Rebase current branch onto main
git rebase main
# Interactive rebase (edit last 3 commits)
git rebase -i HEAD~3
# During interactive rebase, you can:
# pick - use commit
# reword - change commit message
# edit - stop to amend commit
# squash - combine with previous
# fixup - combine, discard message
# drop - remove commit
# Continue after resolving conflicts
git rebase --continue
# Abort rebase
git rebase --abort
Git Cherry-Pick:
Apply specific commits from one branch to another:
# Apply single commit
git cherry-pick abc123
# Apply multiple commits
git cherry-pick abc123 def456
# Apply range of commits
git cherry-pick abc123..def456
# Cherry-pick without committing
git cherry-pick -n abc123
Git Bisect:
Find the commit that introduced a bug:
# Start bisect
git bisect start
# Mark current commit as bad
git bisect bad
# Mark known good commit
git bisect good abc123
# Git checkouts middle commit
# Test and mark as good or bad
git bisect good # or git bisect bad
# Continue until bug commit found
# End bisect
git bisect reset
Git Reflog:
Recovery tool - shows history of HEAD changes:
# Show reflog
git reflog
# Recover lost commit
git checkout HEAD@{2}
# Reset to previous state
git reset --hard HEAD@{5}
Git Tags and Releases
Tags mark specific points in history, typically for releases:
Creating Tags:
# Lightweight tag
git tag v1.0.0
# Annotated tag (recommended)
git tag -a v1.0.0 -m "Release version 1.0.0"
# Tag specific commit
git tag -a v1.0.0 abc123 -m "Release version 1.0.0"
# List tags
git tag
# Show tag details
git show v1.0.0
Working with Tags:
# Push single tag
git push origin v1.0.0
# Push all tags
git push origin --tags
# Delete local tag
git tag -d v1.0.0
# Delete remote tag
git push origin --delete v1.0.0
# Checkout tag
git checkout v1.0.0
# Create branch from tag
git checkout -b release-1.0 v1.0.0
Git Best Practices for Professional Development
1. Write Clear Commit Messages:
# Good commit messages
git commit -m "Fix: Resolve null pointer in user authentication"
git commit -m "Feature: Add email notification system"
git commit -m "Docs: Update API documentation for v2.0"
# Use conventional commits
git commit -m "feat: add user profile page"
git commit -m "fix: correct calculation in shopping cart"
git commit -m "docs: update README with installation steps"
git commit -m "refactor: optimize database queries"
git commit -m "test: add unit tests for auth service"
2. Keep Commits Small and Focused:
# Bad - multiple unrelated changes
git add .
git commit -m "Fix bugs and add features"
# Good - separate commits
git add auth.js
git commit -m "Fix: Correct password validation logic"
git add profile.js profile.css
git commit -m "Feature: Add user profile editing"
3. Use .gitignore:
# Create .gitignore file
touch .gitignore
# Common patterns
echo "node_modules/" >> .gitignore
echo "*.log" >> .gitignore
echo ".env" >> .gitignore
echo "dist/" >> .gitignore
echo ".DS_Store" >> .gitignore
# Check ignored files
git status --ignored
4. Regular Commits and Pulls:
# Pull before starting work
git pull origin main
# Commit regularly
git add .
git commit -m "WIP: implementing feature"
# Pull before pushing
git pull origin main
git push origin feature-branch
5. Branch Naming Conventions:
# Feature branches
git checkout -b feature/user-authentication
git checkout -b feature/payment-integration
# Bug fixes
git checkout -b bugfix/login-error
git checkout -b hotfix/security-patch
# Releases
git checkout -b release/v2.0.0
Real-world Git Workflow Examples
Scenario 1: Team Collaboration on a Web Application
# Developer A - Working on authentication
git checkout main
git pull origin main
git checkout -b feature/auth-system
# Make changes
# ... code ...
git add .
git commit -m "feat: implement JWT authentication"
git push origin feature/auth-system
# Developer B - Working on dashboard
git checkout main
git pull origin main
git checkout -b feature/dashboard
# Make changes
# ... code ...
git add .
git commit -m "feat: create user dashboard"
git push origin feature/dashboard
# Team Lead - Review and merge
git checkout main
git pull origin main
git merge feature/auth-system
git merge feature/dashboard
git push origin main
Scenario 2: Hotfix in Production
# Critical bug in production!
git checkout main
git pull origin main
git checkout -b hotfix/payment-bug
# Fix the bug quickly
vim payment.js
git add payment.js
git commit -m "hotfix: fix payment processing error"
# Push and create PR
git push origin hotfix/payment-bug
# After review, merge to main
git checkout main
git merge hotfix/payment-bug
git push origin main
# Also merge to develop
git checkout develop
git merge hotfix/payment-bug
git push origin develop
Scenario 3: Feature Development with Code Review
# Start feature
git checkout develop
git pull origin develop
git checkout -b feature/social-login
# Work on feature with multiple commits
git add oauth.js
git commit -m "feat: add OAuth configuration"
git add login.js login.css
git commit -m "feat: implement Google login"
git add facebook-auth.js
git commit -m "feat: add Facebook login"
# Squash commits before PR
git rebase -i HEAD~3
# Mark commits as 'squash'
# Push for review
git push origin feature/social-login
# Address review comments
git add oauth.js
git commit -m "fix: update OAuth scope permissions"
git push origin feature/social-login
# After approval
git checkout develop
git merge --no-ff feature/social-login
git push origin develop
Common Git Mistakes and How to Fix Them
1. Accidentally Committed to Wrong Branch:
# Move commit to correct branch
git checkout correct-branch
git cherry-pick main
git checkout main
git reset --hard HEAD~1
2. Forgot to Add File to Last Commit:
# Add file to previous commit
git add forgotten-file.js
git commit --amend --no-edit
3. Wrong Commit Message:
# Change last commit message
git commit --amend -m "New correct message"
# Change older commit message
git rebase -i HEAD~3
# Mark commit as 'reword'
4. Committed Sensitive Data:
# Remove file from history (if not pushed)
git rm --cached .env
git commit -m "Remove sensitive file"
# If already pushed, use BFG Repo-Cleaner
# or git filter-branch (advanced)
5. Merge Conflicts During Pull:
# Option 1: Merge
git pull origin main
# Resolve conflicts
git add .
git commit
# Option 2: Rebase
git pull --rebase origin main
# Resolve conflicts
git add .
git rebase --continue
Git vs Other Version Control Systems
| Feature | Git | SVN (Subversion) | Mercurial | Perforce |
|---|---|---|---|---|
| Architecture | Distributed | Centralized | Distributed | Centralized |
| Speed | Very Fast | Slower | Fast | Fast |
| Branching | Lightweight | Heavy | Lightweight | Heavy |
| Learning Curve | Steep | Moderate | Moderate | Steep |
| Offline Work | Full Support | Limited | Full Support | Limited |
| Storage | Efficient | Less Efficient | Efficient | Moderate |
| Community | Huge | Large | Moderate | Small |
| Price | Free | Free | Free | Paid |
Frequently Asked Questions (FAQs)
1. What's the difference between Git and GitHub?
Git is the version control system (software) that tracks changes in your code. GitHub is a web-based platform that hosts Git repositories and adds features like pull requests, issues, and project management. Think of Git as the engine and GitHub as the car dealership. Other platforms like GitLab and Bitbucket also host Git repositories. Learn more at GitHub Education.
2. How do I undo a commit that's already been pushed?
For commits already pushed to a shared branch, use git revert HEAD to create a new commit that undoes the changes. This preserves history. For local commits, use git reset --soft HEAD~1 to undo while keeping changes, or git reset --hard HEAD~1 to discard changes completely.
3. What should I do when I get a merge conflict?
Don't panic! Merge conflicts happen when Git can't automatically combine changes. Open the conflicted files, look for conflict markers (<<<<<<<, =======, >>>>>>>), decide which code to keep, remove the markers, then git add and git commit to complete the merge.
4. What's the difference between git pull and git fetch?
git fetch downloads changes from the remote repository but doesn't merge them into your current branch. git pull does both fetch and merge in one command. Use fetch when you want to review changes before merging them.
5. How often should I commit?
Commit early and often! Make a commit whenever you complete a logical unit of work - fix a bug, add a feature, refactor code. Think of commits as save points in a video game. Smaller, focused commits are easier to understand and revert if needed.
6. Can I change commit history?
Yes, but be careful! You can change local history using commands like git rebase, git commit --amend, and git reset. However, never change history that's been pushed to a shared branch, as it will cause problems for other developers.
7. What's the best branching strategy?
It depends on your team and project. GitHub Flow is simple and works well for continuous deployment. GitFlow is more complex but good for scheduled releases. The key is consistency - pick a strategy and stick with it.
Conclusion
Congratulations! You've now mastered Git from basics to advanced concepts. Git is more than just a tool - it's an essential skill that will make you a better developer. Whether you're working solo or in a team, Git helps you code with confidence, knowing you can always revert mistakes and collaborate effectively.
Remember:
- Commit often with clear messages
- Use branches for new features
- Pull before you push
- Don't be afraid to experiment - Git has your back
- Practice makes perfect
Keep this guide bookmarked as a reference. The more you use Git, the more natural it becomes. Start applying these concepts in your next project, and you'll soon wonder how you ever coded without it!
Next Steps:
- Set up your first GitHub repository
- Contribute to an open source project
- Implement a branching strategy in your team
- Explore Git hooks for automation
- Learn CI/CD integration with Git
For more in-depth learning, check out the free Pro Git Book and keep practicing!
Happy coding, and may your commits always be green! 🚀
Found this tutorial helpful? Check out more programming guides on Knowledge Mark G: