Git & GitHub

Complete Interactive Tutorial for Developers

Master version control and collaborative development with hands-on examples

Table of Contents

1. Introduction to Version Control

Version control is a system that records changes to files over time so that you can recall specific versions later. It's essential for software development and collaboration.

Track Changes

Keep a detailed history of all changes made to your code, including who made them and when.

Collaboration

Multiple developers can work on the same project simultaneously without conflicts.

Backup & Recovery

Never lose your work. Revert to previous versions if something goes wrong.

Why Version Control Matters

Pro Tip: Version control is not just for code! You can use it for any text-based files including documentation, configuration files, and even this tutorial!

Quick Quiz: What is the primary purpose of version control?

A) To make code run faster
B) To compress files
C) To track changes and enable collaboration
D) To write better code

2. Git Fundamentals

Git is a distributed version control system that tracks changes in source code during software development. It's designed for speed, data integrity, and support for distributed workflows.

Key Git Concepts

Repository (Repo)

A directory containing your project files and the entire history of changes. Can be local or remote.

Commit

A snapshot of your project at a specific point in time. Each commit has a unique ID and message.

Branch

A parallel version of your repository. Allows you to work on different features independently.

Merge

The process of combining changes from different branches into a single branch.

Git Workflow Overview

Basic Git Workflow
Working Directory
Staging Area
Repository
Working Directory

This is where you edit your files. Changes here are not yet tracked by Git.

Staging Area (Index)

A holding area for changes you want to include in your next commit. Use git add to stage files.

Repository

The Git database where your project history is stored. Use git commit to save staged changes.

Installing Git

Installation: Download Git from git-scm.com and follow the installation instructions for your operating system.
# Verify Git installation git --version # Configure Git with your identity git config --global user.name "Your Name" git config --global user.email "your.email@example.com" # Check your configuration git config --list

Quick Quiz: What are the three main areas in Git workflow?

A) Local, Remote, Cloud
B) Working Directory, Staging Area, Repository
C) Master, Branch, Merge
D) Add, Commit, Push

3. GitHub Fundamentals

GitHub is a cloud-based hosting service for Git repositories. It provides a web-based interface for Git and adds collaboration features like issue tracking, project management, and code review.

GitHub vs Git

Git
  • Version control system
  • Command-line tool
  • Works locally
  • Distributed
  • Free and open source
GitHub
  • Hosting service for Git repositories
  • Web-based interface
  • Cloud-based
  • Collaboration features
  • Free tier + paid plans

Key GitHub Features

Code Hosting

Store your Git repositories in the cloud with unlimited public repositories.

Pull Requests

Propose changes to a repository and collaborate on code review before merging.

Issue Tracking

Track bugs, feature requests, and other project-related discussions.

Collaboration

Work with team members, assign tasks, and manage project permissions.

GitHub Actions

Automate your workflow with CI/CD pipelines and automated testing.

GitHub Pages

Host static websites directly from your GitHub repositories.

Creating Your First Repository

Interactive Demo: Create a Repository

Follow these steps to create your first GitHub repository:

Sign Up for GitHub

Visit github.com and create a free account.

Create New Repository

Click the "+" icon in the top right corner and select "New repository".

Configure Repository
  • Choose a repository name (e.g., "my-first-repo")
  • Add a description (optional)
  • Choose public or private
  • Initialize with a README file
Clone to Local Machine
git clone https://github.com/yourusername/my-first-repo.git
Important: Never commit sensitive information like passwords, API keys, or personal data to a public repository!

4. Essential Git Commands

Master these fundamental Git commands to manage your repositories effectively. Each command is explained with practical examples.

Repository Setup

# Initialize a new Git repository git init # Clone an existing repository git clone https://github.com/user/repo.git # Clone to a specific folder git clone https://github.com/user/repo.git my-project

Basic File Operations

# Check repository status git status # Add files to staging area git add filename.txt # Add specific file git add . # Add all files git add *.js # Add all JavaScript files # Commit changes git commit -m "Your commit message" # Add and commit in one command git commit -am "Your commit message"

Viewing History

# View commit history git log # View compact log git log --oneline # View graphical log git log --graph --oneline --all # View changes in a specific commit git show commit-hash # View differences git diff # Working directory vs staging area git diff --staged # Staging area vs last commit git diff HEAD~1 # Compare with previous commit

Branching and Merging

# List branches git branch # Local branches git branch -r # Remote branches git branch -a # All branches # Create new branch git branch feature-branch # Switch to branch git checkout feature-branch # Create and switch to new branch git checkout -b feature-branch # Merge branch git checkout main git merge feature-branch # Delete branch git branch -d feature-branch

Remote Repository Operations

# Add remote repository git remote add origin https://github.com/user/repo.git # View remote repositories git remote -v # Push changes to remote git push origin main # Pull changes from remote git pull origin main # Fetch changes (without merging) git fetch origin

Undoing Changes

# Unstage a file git reset filename.txt # Discard changes in working directory git checkout -- filename.txt # Revert a commit (creates new commit) git revert commit-hash # Reset to previous commit (dangerous!) git reset --hard HEAD~1 # Reset to specific commit git reset --hard commit-hash
Warning: Commands like git reset --hard can permanently delete your work. Always make sure you have backups or your changes are committed before using destructive commands.

Command Practice

Test your knowledge of Git commands:

What command would you use to create a new branch called "feature-login"?

A) git create feature-login
B) git new-branch feature-login
C) git branch feature-login
D) git checkout feature-login

How do you stage all modified files for commit?

A) git commit -a
B) git add .
C) git stage *
D) git add-all

5. Git Workflows

Learn popular Git workflows that teams use to collaborate effectively. Choose the right workflow for your project size and team structure.

Centralized Workflow

Best for: Small teams, simple projects

Everyone works on the main branch. Simple but can lead to conflicts with multiple developers.

main branch
# Centralized workflow commands git clone https://github.com/team/project.git git add . git commit -m "Add new feature" git pull origin main # Get latest changes git push origin main # Push your changes

Feature Branch Workflow

Best for: Medium teams, organized development

Each feature is developed in its own branch. Features are merged back to main via pull requests.

main
feature-A
feature-B
# Feature branch workflow git checkout -b feature-login # Create feature branch git add . git commit -m "Implement login" git push origin feature-login # Push feature branch # Create pull request on GitHub # After review and approval, merge via GitHub git checkout main git pull origin main # Get merged changes git branch -d feature-login # Delete local feature branch

Gitflow Workflow

Best for: Large teams, scheduled releases

Structured workflow with specific branches for development, features, releases, and hotfixes.

Branch Types:
  • main: Production-ready code
  • develop: Integration branch
  • feature/*: New features
  • release/*: Prepare releases
  • hotfix/*: Emergency fixes
Workflow Steps:
  1. Create feature branch from develop
  2. Work on feature
  3. Merge back to develop
  4. Create release branch
  5. Merge release to main and develop
# Gitflow workflow commands git flow init # Initialize gitflow git flow feature start login # Start new feature git flow feature finish login # Finish feature git flow release start v1.0 # Start release git flow release finish v1.0 # Finish release git flow hotfix start urgent-fix # Start hotfix git flow hotfix finish urgent-fix # Finish hotfix

GitHub Flow

Best for: Continuous deployment, web applications

Simplified workflow focusing on main branch with feature branches and pull requests.

Create Branch

Create a feature branch from main for your work.

Add Commits

Make changes and commit them to your feature branch.

Open Pull Request

Open a pull request to propose your changes.

Review & Discuss

Team reviews code and discusses changes.

Deploy & Test

Deploy from the feature branch to test in production-like environment.

Merge

Once approved and tested, merge to main and deploy.

Choosing a Workflow: Start simple with GitHub Flow or Feature Branch workflow. Move to Gitflow only if you need structured releases and have a large team.

6. Best Practices

Follow these proven practices to maintain clean, professional repositories and collaborate effectively with your team.

Commit Message Guidelines

Writing Great Commit Messages

Good commit messages make your project history readable and useful.

# Good commit message structure: # # (): # # # #
# Examples: feat(auth): add login functionality fix(ui): correct button alignment on mobile docs(readme): update installation instructions refactor(api): optimize user data fetching test(utils): add unit tests for validation helpers
Do:
  • Use present tense ("add" not "added")
  • Keep subject line under 50 characters
  • Capitalize the subject line
  • Don't end with a period
  • Use imperative mood
Don't:
  • Write vague messages like "fix bug"
  • Use past tense
  • Include unnecessary details in subject
  • Use periods in subject line
  • Commit without a message

Repository Structure

project-root/ ├── README.md # Project overview and setup instructions ├── .gitignore # Files to ignore in version control ├── LICENSE # License information ├── package.json # Project dependencies (if applicable) ├── src/ # Source code directory │ ├── components/ # Reusable components │ ├── utils/ # Utility functions │ └── index.js # Main entry point ├── tests/ # Test files ├── docs/ # Documentation └── assets/ # Static assets (images, fonts)

Branch Naming Conventions

Consistent Branch Names
Feature Branches:
  • feature/user-authentication
  • feature/shopping-cart
  • feat/api-integration
Bug Fix Branches:
  • fix/login-error
  • bugfix/mobile-layout
  • hotfix/security-patch

Essential Files

README.md

The front page of your repository. Should include:

  • Project description
  • Installation instructions
  • Usage examples
  • Contributing guidelines
  • License information
.gitignore

Prevent unwanted files from being committed:

  • Build artifacts
  • Dependencies (node_modules)
  • Environment files (.env)
  • IDE configuration files
  • OS-specific files (.DS_Store)
# Example .gitignore file # Dependencies node_modules/ vendor/ # Build outputs dist/ build/ *.min.js # Environment files .env .env.local .env.production # IDE files .vscode/ .idea/ *.swp *.swo # OS files .DS_Store Thumbs.db # Logs *.log logs/

Security Best Practices

Security Checklist:
  • Never commit passwords, API keys, or sensitive data
  • Use environment variables for configuration
  • Review code before merging pull requests
  • Keep dependencies updated
  • Use signed commits for verified authorship
  • Enable two-factor authentication on GitHub

Code Review Guidelines

Effective Code Reviews
For Authors:
  • Keep pull requests small and focused
  • Write clear descriptions
  • Test your changes thoroughly
  • Respond to feedback constructively
  • Update documentation if needed
For Reviewers:
  • Review code promptly
  • Be constructive and specific
  • Check for functionality and style
  • Verify tests are included
  • Approve when satisfied

Quick Quiz: Which is a good commit message?

A) "fixed stuff"
B) "Updated the login page and also fixed a bug in the header component and changed some styling"
C) "fix(auth): resolve login validation error"
D) "changes made to files"

7. Interactive Examples

Practice Git concepts with these interactive scenarios. Each example simulates real-world situations you'll encounter as a developer.

Scenario 1: Your First Contribution

Scenario: Contributing to an Open Source Project

You want to contribute to an open source project. Follow the complete workflow:

Fork the Repository

Go to the project's GitHub page and click "Fork" to create your own copy.

Navigate to: https://github.com/original-owner/project
Clone Your Fork
git clone https://github.com/your-username/project.git
cd project
Add Upstream Remote
git remote add upstream https://github.com/original-owner/project.git
git remote -v
Create Feature Branch
git checkout -b fix-typo-in-readme
Make Your Changes

Edit the README.md file to fix the typo, then:

git add README.md
git commit -m "docs(readme): fix typo in installation section"
Push to Your Fork
git push origin fix-typo-in-readme
Create Pull Request

Go to your fork on GitHub and click "New Pull Request". Write a clear description of your changes.

Scenario 2: Handling Merge Conflicts

Scenario: Resolving Merge Conflicts

Two developers modified the same file. Learn how to resolve conflicts:

The Conflict Occurs

When you try to merge or pull, Git shows a conflict:

git merge feature-branch
Output: Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.
View Conflict Markers

Open the conflicted file. Git adds conflict markers:

<!DOCTYPE html> <html> <head> <title> <<<<<<< HEAD My Amazing Website ======= My Awesome Website >>>>>>> feature-branch </title> </head> <body> <h1>Welcome!</h1> </body> </html>
Resolve the Conflict

Edit the file to resolve the conflict. Choose one version or combine both:

<!DOCTYPE html> <html> <head> <title>My Amazing Website</title> </head> <body> <h1>Welcome!</h1> </body> </html>
Mark as Resolved
git add index.html
git commit -m "resolve merge conflict in page title"

Scenario 3: Emergency Hotfix

Scenario: Emergency Production Fix

Critical bug in production needs immediate fix while development continues:

Create Hotfix Branch

Create a hotfix branch from the main branch:

git checkout main
git pull origin main
git checkout -b hotfix/critical-security-patch
Implement Quick Fix

Make the minimal necessary changes to fix the issue:

git add security-patch.js
git commit -m "hotfix: patch security vulnerability in auth module"
Test the Fix

Run tests to ensure the fix works and doesn't break anything:

npm test
Deploy to Production
git checkout main
git merge hotfix/critical-security-patch
git push origin main
Merge Back to Development

Ensure the fix is also in the development branch:

git checkout develop
git merge hotfix/critical-security-patch
git push origin develop
Clean Up
git branch -d hotfix/critical-security-patch
git push origin --delete hotfix/critical-security-patch

Git Command Simulator

Command Line Simulator

Practice Git commands in a safe environment:

# Current repository state: # - Branch: main # - Status: clean # - Remote: origin (https://github.com/user/repo.git) $ git status On branch main Your branch is up to date with 'origin/main'. nothing to commit, working tree clean
$
Try commands like: git status, git branch, git log --oneline, git add ., git commit -m "message"

8. Summary & Next Steps

Congratulations! You've completed the Git and GitHub tutorial. Here's what you've learned and where to go next.

What You've Learned

Core Concepts
  • Version control fundamentals
  • Git repository structure
  • Working directory, staging area, and commits
  • Branches and merging
  • Remote repositories
Practical Skills
  • Essential Git commands
  • GitHub collaboration features
  • Pull request workflow
  • Conflict resolution
  • Best practices and conventions

Quick Reference

Most Used Commands
Daily Commands:
  • git status
  • git add .
  • git commit -m "message"
  • git push
  • git pull
Branching:
  • git branch
  • git checkout -b branch
  • git merge branch
  • git branch -d branch
Information:
  • git log
  • git diff
  • git show
  • git remote -v

Next Steps

Advanced Git
  • Interactive rebasing
  • Cherry-picking commits
  • Git hooks
  • Submodules
  • Advanced merging strategies
DevOps Integration
  • GitHub Actions (CI/CD)
  • Automated testing
  • Deployment pipelines
  • Code quality tools
  • Security scanning
Team Collaboration
  • Code review best practices
  • Issue tracking and project management
  • Documentation strategies
  • Open source contribution
  • Team workflow optimization

Additional Resources

Practice Makes Perfect: The best way to learn Git is to use it daily. Start with simple projects and gradually work on more complex scenarios. Don't be afraid to experiment with branches – you can always start over!

Congratulations!

You've completed the Git and GitHub tutorial. You now have the foundation to use version control effectively in your development projects.

Remember: Git is a powerful tool with many features. Start with the basics and gradually explore advanced features as you become more comfortable.