The Complete Git and GitHub Guide: From Beginner to Pro Developer

August 11, 2024 (11mo ago)

The Complete Git and GitHub Guide: From Beginner to Pro Developer

Today, I'm sharing everything you need to know about version control – from your first git init to advanced rebasing strategies that will make you a Git power user.

Whether you're just starting your coding journey or looking to level up your Git skills, this guide covers the essential 80% of Git knowledge that you'll use in 99% of your daily development work.

What is Git and Why Should You Care?

Git is a Version Control System that tracks changes in your files over time. Think of it as a time machine for your code – you can see what changed, when it changed, and easily revert to previous versions when things go wrong.

Here's the learning path I recommend:

  1. Get the basics - Learn fundamental commands
  2. Use it daily - Practice with real projects
  3. Face problems - Encounter real-world scenarios
  4. Solve problems - Build confidence through experience

The beauty of Git is that once you understand the core concepts, you'll wonder how you ever coded without it.

Setting Up Your Git Environment

Before we dive into commands, let's get your system ready:

# Check if Git is installed
git --version
 
# Configure your identity (required for commits)
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
 
# Set VS Code as your default editor (optional)
git config --global core.editor "code --wait"

These configurations are global, meaning they'll apply to all your Git repositories on this machine.

Understanding Git's Core Workflow

Git has three main areas where your files can exist:

  1. Working Directory - Where you edit files
  2. Staging Area - Where you prepare changes for commit
  3. Repository - Where Git stores your project history

Here's the basic workflow:

# Initialize a new Git repository (one time per project)
git init
 
# This creates a hidden .git folder that stores all your project history
# Check repository status
git status
 
# Add files to staging area
git add filename.txt
# Or add all files
git add .
 
# Commit your changes with a descriptive message
git commit -m "Add user authentication feature"
 
# Check your commit history
git log
# Or get a condensed view
git log --oneline

The Art of Atomic Commits

One of the most important habits you can develop is making atomic commits. Each commit should focus on:

This makes your project history clean and makes it easier to track down issues later.

Commit Message Best Practices

There are two schools of thought for commit messages:

Present Tense (Imperative):

git commit -m "Add user login functionality"
git commit -m "Fix navigation menu bug"
git commit -m "Update README with installation steps"

Past Tense:

git commit -m "Added user login functionality"
git commit -m "Fixed navigation menu bug"
git commit -m "Updated README with installation steps"

Choose one style and stick with it. I prefer the past style because it tells that codebase the commit is applied or changes have been made at that point/commit.

Ignoring Files with .gitignore

Not all files should be tracked by Git. Create a .gitignore file in your project root to exclude:

# Dependencies
node_modules/
*.log
 
# Environment variables
.env
.env.local
 
# Build outputs
dist/
build/
 
# IDE files
.vscode/
.idea/
 
# OS files
.DS_Store
Thumbs.db

Pro Tip: Get templates online for your specific technology stack. The patterns can be tricky to get right, so don't reinvent the wheel.

Understanding Git Branches

Branches are like alternative timelines for your project. You're always on some branch – by default, it's called main (formerly master).

# See all branches
git branch
 
# Create a new branch
git branch bugfix
 
# Switch to a branch
git switch bugfix
 
# Create and switch in one command
git switch -c dark-mode
# or the older syntax
git checkout -b dark-mode
 
# Check your current location
git log --oneline

The HEAD Pointer

HEAD points to where your current branch is. You can see this by checking the .git/HEAD file in your repository.

Important: Always commit your changes before switching branches, or Git will prevent you from switching to avoid losing work.

Merging Branches

Once you've completed work on a feature branch, you'll want to merge it back into your main branch:

# Switch to the target branch (usually main)
git switch main
 
# Merge your feature branch
git merge bugfix

Git will attempt one of two types of merges:

Fast-Forward Merge

When the main branch hasn't changed since you created your feature branch, Git simply moves the main pointer forward.

Non-Fast-Forward Merge

When both branches have new commits, Git creates a merge commit with two parents.

Handling Merge Conflicts

Sometimes Git can't automatically resolve conflicts. When this happens, you'll see conflict markers in your files:

<<<<<<< HEAD
# Your current branch changes
=======
# Changes from the branch you're merging
>>>>>>> feature-branch

To resolve:

  1. Edit the file to keep what you want
  2. Remove the conflict markers (<<<<<<<, =======, >>>>>>>)
  3. Save the file
  4. Add and commit the resolved file

Git Diff: Understanding Changes

The git diff command shows you what's changed:

# Compare working directory with staging area
git diff
 
# Compare staging area with last commit
git diff --staged

Reading diff output:

but that also depends on the order of diff commit command.This depends on argument order.

the meaning of --- (old) and +++ (new) in a diff output does depend on how you run the diff or git diff command, especially the order of the arguments.

🧾 Examples

Basic diff:

diff old.txt new.txt

Git diff (commits):

git diff commit1 commit2

Reverse order:

git diff commit2 commit1

Key: The first argument is treated as old (---), second as new (+++).


Git Stash: Temporary Storage

Sometimes you need to switch branches but aren't ready to commit your current changes:

# Stash your current changes
git stash
 
# Now you can switch branches safely
git switch other-branch
 
# Later, bring back your stashed changes
git stash pop
 
# Or apply changes but keep them in stash
git stash apply

Advanced Git Commands

Checking Out Specific Commits

# Go to a specific commit (detached HEAD state)
git checkout <commit-hash>
 
# Go back 2 commits from current position
git checkout HEAD~2
 
# Re-attach HEAD to main branch
git switch main

Restoring Files

# Restore a file to its last committed version
git restore filename.txt

Git Rebase: The Clean-Up Tool

Rebasing is an alternative to merging that creates a cleaner project history:

# Basic rebase workflow
git init
# Work and commit on main branch
 
git switch -c footer
# Work and commit on feature branch
 
git switch main
# More work on main branch
 
git switch footer
git rebase main  # This replays your footer commits on top of main

Interactive Rebase

Clean up your commit history before sharing:

git rebase -i HEAD~5

This opens an editor where you can:

⚠️ Critical Warning: Never rebase commits that you've already pushed to a shared repository. This rewrites history and can cause problems for other developers.Also, Never run rebase command on main/master branch.

Git Tags: Marking Important Points

Tags are like sticky notes for important commits (usually releases):

# List all tags
git tag
 
# Create a lightweight tag
git tag v1.0.1
 
# Create an annotated tag (recommended)
git tag -a v2.0.0 -m "Version 2.0.0 release"
 
# Tag a previous commit
git tag v1.5.0 9fceb02
 
# Show tag information
git show v2.0.0
 
# Delete a tag
git tag -d v1.5.0
 
# Push tags to remote
git push --tags

Git Reflog: Your Safety Net

Git keeps track of where your HEAD pointer moves:

git reflog show HEAD

This shows a log of all your branch switches, commits, and resets. These logs are local only and eventually expire, but they're invaluable for recovering from mistakes.

GitHub: Git in the Cloud

Git is the software, GitHub is a service that hosts Git repositories online. GitHub provides:

Alternatives include GitLab and Bitbucket.

Setting Up GitHub Authentication

GitHub requires SSH keys for code pushing (password authentication is deprecated):

# Check for existing SSH keys
ls -al ~/.ssh
 
# Generate a new SSH key (follow GitHub's instructions for your OS)
ssh-keygen -t ed25519 -C "your_email@example.com"
 
# Add SSH key to ssh-agent
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

Then add your public key to your GitHub account settings.

Working with Remote Repositories

# Clone a repository
git clone https://github.com/username/repository.git
 
# View remote connections
git remote -v
 
# Add a remote repository
git remote add origin https://github.com/username/repository.git
 
# Rename a remote
git remote rename origin upstream
 
# Remove a remote
git remote remove origin
 
# Push to remote
git push origin main
 
# Set upstream for easier future pushes
git push -u origin main
# Now you can just use: git push

Syncing with Remote Repositories

When you clone a repository, you only get the main branch locally. Other remote branches exist but aren't configured:

# List all branches (including remote)
git branch -a
 
# Switch to a remote branch (automatically sets up tracking)
git switch feature-branch

Fetching vs. Pulling

Understanding the difference is crucial:

# Fetch: Download changes but don't merge
git fetch origin
 
# Pull: Fetch + merge in one command
git pull origin main
# Equivalent to: git fetch + git merge

Use git fetch when you want to see what's changed before merging. Use git pull when you're ready to integrate changes immediately.

Essential GitHub Features

Beyond basic Git operations, GitHub offers powerful collaboration features:

Repository Management

Development Tools

Quick Reference Cheat Sheet

Here are the commands you'll use 90% of the time:

# Daily workflow
git status          # Check current state
git add .           # Stage all changes
git commit -m "msg" # Commit with message
git push           # Push to remote
git pull           # Pull latest changes
 
# Branch management
git branch          # List branches
git switch -c name  # Create and switch branch
git merge branch    # Merge branch
git branch -d name  # Delete branch
 
# Troubleshooting
git log --oneline   # View commit history
git diff           # See changes
git stash          # Temporarily store changes
git restore file   # Undo file changes

Pro Tips for Git Mastery

  1. Commit early, commit often - Small, frequent commits are easier to manage than large ones
  2. Write meaningful commit messages - Your future self will thank you
  3. Use branches for everything - Even small changes deserve their own branch
  4. Keep your main branch clean - Always work on feature branches
  5. Review before you commit - Use git diff --staged to see exactly what you're committing
  6. Learn to read Git output - Git's messages are usually helpful if you take time to read them
  7. Don't panic - Git rarely loses data permanently. With reflog and proper backups, most mistakes are recoverable

Common Pitfalls to Avoid

Conclusion

Git & GitHub are essential tools for modern developers. Start with the basics: init, add, commit, push, and pull. Once you're comfortable, explore branching and merging.

You don’t need to memorize every command—just understand the core concepts. Use Git daily, create repos, experiment, and learn from mistakes.

Start today: run git init on your project and commit your first change.


Want to dive deeper into modern web development? Check out my other
Related Posts: