What is Git?

Git is the world’s most popular version control system, used by millions of developers to track changes in their code, collaborate with team members, and manage software development projects. Created by Linus Torvalds in 2005, Git has become an essential tool for modern software development.

GitHub, on the other hand, is a cloud-based hosting service for Git repositories that adds collaboration features, issue tracking, and code review capabilities. Together, Git and GitHub form the backbone of modern software development workflows.

Why Use Git and GitHub?

1. Version Control and History

Git tracks every change made to your codebase, allowing you to:

– Review the complete history of your project
– Revert to previous versions when needed
– Understand who made which changes and why
– Track when bugs were introduced

2. Collaboration

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

– Branch-based development enables parallel work
– Pull requests facilitate code review
– Merge conflicts are managed systematically
– Team members can work offline and sync later

3. Backup and Recovery

Your code is safely stored in multiple locations:

– Local repository on your machine
– Remote repository on GitHub
– Other team members’ local copies
– Easy disaster recovery

4. Professional Development

– GitHub profiles serve as portfolios for developers
– Open source contributions demonstrate skills
– Collaboration experience is visible to employers
– Industry-standard tool knowledge

Installing Git

Windows

Download Git from git-scm.com and run the installer. Use Git Bash for command-line operations.

Mac

Install via Homebrew:

brew install git

Or download from git-scm.com.

Linux

# Ubuntu/Debian
sudo apt-get install git

# Fedora
sudo dnf install git

# Arch
sudo pacman -S git

Verify Installation

git --version

Git Configuration

Set up your identity (required before first commit):

git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

Configure default branch name:

git config --global init.defaultBranch main

View all configuration:

git config --list

Git Fundamentals

Creating a Repository

Initialize a new repository:

mkdir my-project
cd my-project
git init

Clone an existing repository:

git clone https://github.com/username/repository.git

The Git Workflow

Git has three main states for files:

1. Working Directory: Where you edit files
2. Staging Area (Index): Where you prepare files for commit
3. Repository (HEAD): Where commits are stored

Basic Git Commands

Check status:

git status

Add files to staging area:

# Add specific file
git add filename.txt

# Add all changed files
git add .

# Add all files in directory
git add src/

Commit changes:

git commit -m "Add new feature"

View commit history:

git log
git log --oneline
git log --graph --oneline --all

View changes:

# Changes in working directory
git diff

# Changes in staging area
git diff --staged

# Changes between commits
git diff commit1 commit2

Branching and Merging

Branches allow you to develop features independently from the main codebase.

Branch Operations

Create a new branch:

git branch feature-login

Switch to a branch:

git checkout feature-login

# Or create and switch in one command
git checkout -b feature-login

Modern alternative (Git 2.23+):

git switch feature-login
git switch -c feature-login

List branches:

git branch
git branch -a  # Include remote branches

Delete a branch:

git branch -d feature-login  # Safe delete
git branch -D feature-login  # Force delete

Merging

Merge a branch into current branch:

git checkout main
git merge feature-login

Handling Merge Conflicts

When Git can’t automatically merge changes:

1. Git marks conflicted files
2. Open conflicted files and resolve conflicts manually
3. Stage resolved files: git add filename
4. Complete the merge: git commit

Conflict markers look like:

<<<<<<< HEAD
Current branch content
=======
Merging branch content
>>>>>>> feature-branch

Working with Remote Repositories

Connecting to GitHub

Add remote repository:

git remote add origin https://github.com/username/repo.git

View remotes:

git remote -v

Pushing Changes

Push to remote:

git push origin main

# Set upstream for future pushes
git push -u origin main

# Then simply use
git push

Pulling Changes

Fetch and merge changes:

git pull origin main

Fetch without merging:

git fetch origin

GitHub Workflow

Creating a Repository on GitHub

1. Click “New repository” on GitHub
2. Name your repository
3. Choose public or private
4. Optionally add README, .gitignore, and license
5. Click “Create repository”

Connecting Local Repository to GitHub

git remote add origin https://github.com/username/repo.git
git branch -M main
git push -u origin main

Forking and Pull Requests

Forking:

1. Click “Fork” on a GitHub repository
2. Clone your fork locally
3. Make changes and push to your fork
4. Create a pull request to the original repository

Pull Request Workflow:

1. Create a new branch for your feature
2. Make changes and commit
3. Push branch to GitHub
4. Open pull request on GitHub
5. Collaborate on review and feedback
6. Merge when approved

Essential Git Commands Reference

Undoing Changes

Discard changes in working directory:

git checkout -- filename
git restore filename  # Modern alternative

Unstage files:

git reset HEAD filename
git restore --staged filename  # Modern alternative

Amend last commit:

git commit --amend -m "Updated commit message"

Revert a commit:

git revert commit-hash

Reset to previous commit:

git reset --soft HEAD~1  # Keep changes staged
git reset --mixed HEAD~1  # Keep changes unstaged
git reset --hard HEAD~1  # Discard all changes

Stashing

Temporarily save changes without committing:

# Stash changes
git stash

# Stash with message
git stash save "Work in progress"

# List 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}

# Delete stash
git stash drop stash@{0}

# Clear all stashes
git stash clear

Tagging

Mark specific points in history:

# Create lightweight tag
git tag v1.0.0

# Create annotated tag
git tag -a v1.0.0 -m "Version 1.0.0"

# List tags
git tag

# Push tags to remote
git push origin v1.0.0
git push origin --tags  # All tags

Advanced Git Techniques

Rebasing

Rebase rewrites commit history for a cleaner timeline:

git checkout feature-branch
git rebase main

Interactive Rebase:

git rebase -i HEAD~3

Options in interactive rebase:
pick: Use commit as-is
reword: Change commit message
edit: Amend commit
squash: Combine with previous commit
drop: Remove commit

Cherry-Picking

Apply specific commits to current branch:

git cherry-pick commit-hash

Git Aliases

Create shortcuts for common commands:

git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual 'log --graph --oneline --all'

Best Practices

Commit Messages

Write clear, descriptive commit messages:

# Good
git commit -m "Add user authentication with JWT"
git commit -m "Fix memory leak in image processing"

# Bad
git commit -m "Update"
git commit -m "Fixed stuff"

Conventional Commits Format:

type(scope): subject

feat(auth): add JWT authentication
fix(api): resolve timeout issues
docs(readme): update installation instructions
style(header): format navigation menu
refactor(database): optimize query performance
test(api): add integration tests
chore(deps): update dependencies

Branching Strategy

Git Flow:

main: Production-ready code
develop: Integration branch for features
feature/*: New features
hotfix/*: Urgent production fixes
release/*: Release preparation

GitHub Flow (Simpler):

main: Always deployable
feature branches: Branch off main for all changes
– Pull requests for code review
– Merge to main when ready

When to Commit

– Commit often with small, logical changes
– Each commit should be a complete, working state
– Don’t commit half-finished features
– Commit before risky operations

.gitignore Best Practices

Create a .gitignore file to exclude files:

# Dependencies
node_modules/
vendor/

# Environment variables
.env
.env.local

# Build outputs
dist/
build/
*.log

# IDE files
.vscode/
.idea/
*.swp

# OS files
.DS_Store
Thumbs.db

GitHub Features

GitHub Issues

Track bugs, features, and tasks:

– Create issues for bugs or feature requests
– Use labels to categorize
– Assign to team members
– Link to pull requests
– Close with commit messages: “Fixes #123”

GitHub Actions

Automate workflows with CI/CD:

name: CI

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Run tests
        run: npm test

GitHub Pages

Host static websites directly from repositories:

1. Enable GitHub Pages in repository settings
2. Choose source branch (usually main or gh-pages)
3. Access at username.github.io/repository

Common Git Problems and Solutions

Accidentally Committed to Wrong Branch

# Move commit to correct branch
git checkout correct-branch
git cherry-pick commit-hash
git checkout wrong-branch
git reset --hard HEAD~1

Need to Undo Pushed Commit

# Create new commit that undoes changes
git revert commit-hash
git push

Forgot to Add Files to Last Commit

git add forgotten-file.txt
git commit --amend --no-edit

Merge Conflict Resolution

# Abort merge
git merge --abort

# Use their version
git checkout --theirs filename

# Use our version
git checkout --ours filename

Git Security

SSH Keys for GitHub

More secure than HTTPS authentication:

# Generate SSH key
ssh-keygen -t ed25519 -C "your_email@example.com"

# Add to ssh-agent
eval "SSH_AUTH_SOCK=/tmp/ssh-XXXXXXjF9H77/agent.2245045; export SSH_AUTH_SOCK;
SSH_AGENT_PID=2245047; export SSH_AGENT_PID;
echo Agent pid 2245047;"
ssh-add ~/.ssh/id_ed25519

# Add public key to GitHub settings
cat ~/.ssh/id_ed25519.pub

Signing Commits

Verify commit authenticity with GPG:

# Generate GPG key
gpg --gen-key

# Configure Git
git config --global user.signingkey YOUR_KEY_ID
git config --global commit.gpgsign true

# Sign commits
git commit -S -m "Signed commit"

Git Performance Tips

Large Files

Use Git LFS (Large File Storage) for large files:

git lfs install
git lfs track "*.psd"
git add .gitattributes

Shallow Clones

Clone with limited history for faster downloads:

git clone --depth 1 https://github.com/username/repo.git

Learning Resources

Pro Git Book: Free comprehensive guide
GitHub Learning Lab: Interactive tutorials
Git Documentation: Official reference
Atlassian Git Tutorials: Excellent visual guides
Oh Shit, Git!?!: Common problem solutions

Conclusion

Git and GitHub are fundamental tools for modern software development. Mastering these tools enables:

– Effective version control and code management
– Seamless team collaboration
– Professional development workflows
– Open source contribution
– Career advancement in software development

Start with basic commands, practice regularly, and gradually explore advanced features. Don’t be afraid to experiment – Git’s non-destructive nature means you can always recover from mistakes.

Whether you’re building personal projects or working on enterprise applications, Git and GitHub provide the infrastructure needed for professional software development. Consider deploying your applications with reliable hosting providers like Hostinger or Cloudways for seamless Git integration and deployment workflows.