Git and GitHub — the two tools every developer needs to know before anything else
If you've been learning to code for more than a week, you've probably heard the words Git and GitHub thrown around constantly — in tutorials, job listings, and developer forums alike. And if you're anything like most beginners I've talked to, your first reaction was probably: "That sounds complicated. I'll deal with it later."
Here's what I wish someone had told me early on: learning Git is one of the highest-leverage decisions you can make as a developer. It costs you a few hours upfront and saves you from countless disasters down the road — like that time you accidentally overwrote a week's worth of work and had no way to get it back.
In this complete Git and GitHub tutorial for beginners, we'll start from absolute zero. You'll learn what Git actually is, how it differs from GitHub, how to install and configure it, and how to use every essential command in a real project workflow — including the parts most beginner guides skip, like undoing mistakes, comparing versions, and collaborating with a team through pull requests.
I'm Mostafa Amaan, and I cover developer tools and technical infrastructure over at Valley4Techs. Whether you're following a programming learning roadmap or just getting your first project off the ground, mastering Git is non-negotiable. Let's get into it.
- The real difference between Git and GitHub
- Git's three-stage architecture: Working Directory, Staging Area, and Repository
- How to install Git and configure it for the first time
- Core Git commands: from
git initall the way togit push - Branching, merging, and resolving merge conflicts
- Collaborating with your team via GitHub and pull requests
- How to safely undo mistakes (no panic required)
What You Need Before You Start
You don't need to be a coding expert to learn Git — but a few basics will make the experience smoother:
- Basic file navigation: Knowing how to create, rename, and move files and folders on your computer.
- Basic command-line comfort: You should be able to
open a Terminal (macOS/Linux) or Command Prompt / Git Bash (Windows) and run simple commands like
cdto change directories,mkdirto create folders, andtouchto create files. - A code editor: VS Code is the most popular choice and has excellent built-in Git support. Any text editor works though.
That's it. Let's move on.
What Is Git — and Why Does Every Developer Use It?
Git is a version control system — a tool that runs locally on your machine and keeps a complete, time-stamped history of every change you make to your files. Not just code: text documents, configuration files, even design assets.
Here's a scenario that I guarantee will happen to you eventually without Git: You spend two weeks building a feature. Something breaks. You can't figure out what changed. You frantically try to undo things manually and end up making it worse. With Git? You'd issue one command and be back to a working state in about ten seconds.
Git was created by Linus Torvalds — the same person behind the Linux kernel — in 2005. He built it to solve a very real problem his team was having managing thousands of changes to Linux's source code. Since then, it's become the undisputed standard for version control across the entire software industry.
Git vs. GitHub: They Are Not the Same Thing
A common mistake I see all the time with beginners is treating Git and GitHub as interchangeable. They're not. Here's the clearest way I can explain it:
| Aspect | Git | GitHub |
|---|---|---|
| What it is | A tool installed on your local machine | A cloud platform for hosting Git repositories |
| Works offline? | ✅ Yes | ❌ Requires internet |
| Primary purpose | Track changes, manage versions | Share, collaborate, and back up code online |
| Who built it? | Linus Torvalds (2005) | Owned by Microsoft (acquired 2018) |
| Analogy | The coffee | The coffee shop that serves it |
The key takeaway: you can use Git entirely without GitHub. But GitHub without Git is meaningless — it's just a web interface built on top of Git that adds collaboration features like pull requests, issue tracking, and project hosting. Alternatives to GitHub include GitLab and Bitbucket, which use the same underlying Git technology.
How Git Works Internally: The Three-Stage Architecture
Before you type a single command, understanding Git's mental model will save you from enormous confusion later. Git organizes your work into three local stages, plus an optional remote:
- Working Directory: This is your project folder — where you write and edit files. Git watches this area for changes but hasn't saved anything yet.
- Staging Area (Index): A holding zone where you place changes you're ready to commit. Think of it as a shopping cart — you add items before you actually check out.
-
Local Repository: The permanent history store on your machine.
When you run
git commit, everything in staging gets saved here forever.
Once your work is committed locally, you can push it to a
Remote Repository on GitHub using
git push.
To pull someone else's changes down to your machine, you use
git pull.
Git's architecture: your code travels from your machine all the way to GitHub
How to Install Git and Set It Up for the First Time
Installing on Windows
Go to git-scm.com and download the latest installer. Run it and leave all options at their defaults — they're well-chosen for beginners. After installation, you'll have Git Bash available: a Linux-style terminal for running Git commands on Windows.
Installing on macOS
Open Terminal and run:
xcode-select --install.
This installs Git as part of Apple's Command Line Tools. If you use Homebrew, you can also run:
brew install git.
Installing on Linux (Ubuntu/Debian)
sudo apt update && sudo apt install git
First-Time Configuration (Don't Skip This)
After installing Git, the very first thing you need to do is tell it who you are. Every commit you make will carry your name and email — so this is mandatory:
git config --global user.name "Your Name" git config --global user.email "you@example.com"
To verify your setup worked:
git config --list
Core Git Commands — Step by Step
Setting Up a Practice Project
Let's create a real project from scratch so you can follow along. Open your terminal and run these commands one at a time:
cd ~/Desktop # Navigate to the Desktop mkdir git-practice # Create a new project folder cd git-practice # Enter the folder touch index.html style.css # Create two starter files mkdir assets # Create a subfolder cd assets touch logo.png # Create a placeholder file inside it cd .. # Return to the project root
1. Initialize a Repository — git init
You're inside your project folder. Now you need to tell Git to start tracking it:
git init
You'll see: Initialized empty Git repository in .../git-practice/.git/. That
.git
folder is Git's hidden database — it stores your entire project history. One golden rule:
never manually delete or edit anything inside .git. Doing so is
like formatting your hard drive.
2. Check File Status — git status
This is the command I use most often — probably a dozen times a day. It tells you exactly what state your files are in: untracked, modified, or staged.
git status
In my experience, the most common beginner mistake is jumping straight to
git add
without first running git status. Always check the status first — it prevents
accidental commits of files you didn't intend to include.
Create a file named
.gitignore in your project root and list any files or folders
Git should ignore — like node_modules/, .env (which contains API keys
or passwords), or OS-generated files like .DS_Store on macOS. You can find
ready-made templates for any language or framework at
gitignore.io.
3. Stage Your Changes — git add
Once you've made changes you're happy with, move them to the Staging Area:
git add index.html # Stage a single file git add . # Stage all modified files at once git add *.css # Stage all CSS files
4. Save Your Work Permanently — git commit
A commit is a permanent snapshot. Everything in your Staging Area gets frozen in the project's history:
git commit -m "Add homepage HTML structure and base styles"
Write your commit messages in the imperative tense, like a short instruction: "Add login form", "Fix null pointer in auth", "Remove deprecated API endpoint." A message like "fixed stuff" tells future-you absolutely nothing.
-m
in your commit command, Git opens a text editor called Vim in your terminal —
and it's notoriously confusing for newcomers. To escape: press Esc, then type
:wq and hit Enter. Alternatively, you can set VS Code as
your default Git editor by running:
git config --global core.editor "code --wait"
5. View Commit History — git log
Shows all past commits with their author, timestamp, and message:
git log git log --oneline # Compact one-line view per commit git log --oneline --graph # Visual branch tree
The output of git log — each line is a point in time you can return to
6. Delete Files and Untrack Them — git rm
Instead of manually deleting a file and then running git add to register the deletion,
you can do it in one step:
git rm filename.txt # Delete file and stage the deletion git rm --cached filename.txt # Untrack file but keep it on disk
The --cached flag is a lifesaver when you accidentally committed a
.env file or any other sensitive file. It removes the file from Git's tracking
without deleting it from your local machine.
7. Compare Changes Between Commits — git diff
On larger projects, you'll often need to pinpoint exactly what changed between two versions.
Grab two commit IDs from git log and pass them to git diff:
git diff <first-commit-id> <second-commit-id>
Lines in red (prefixed with -) were removed; lines in green (prefixed with
+) were added. Press q to exit the view.
Branching and Merging: Parallel Work Without the Chaos
Branching is one of Git's most powerful features, and it's where things start to feel genuinely magical. The idea: instead of editing your main codebase directly and risking breaking everything, you create a separate "branch" — a parallel copy where you can work freely. When you're done, you merge it back.
Imagine you're building a new user authentication feature while your colleague is fixing a critical bug. You each work in your own branch, completely independently, with zero interference. Then you both merge into the main branch when your respective work is ready. This is exactly how professional development teams operate every single day.
Essential Branching Commands
git branch # List all branches git branch feature-auth # Create a new branch git checkout feature-auth # Switch to that branch git checkout -b feature-auth # Create AND switch in one command git branch -d feature-auth # Delete a branch after merging
Merging Branches — git merge
Once your feature is complete, switch back to main and merge:
git checkout main git merge feature-auth
Handling Merge Conflicts — Don't Panic
A merge conflict happens when two people edit the same line of the same file. Git stops the merge and marks the conflict in the file like this:
<<<<<<< HEAD const user = getUser(); ======= const user = fetchUser(); >>>>>>> feature-auth
Everything above ======= is your current branch's version; everything below is
from the branch you're merging in. Edit the file to keep whichever version (or a combination)
is correct, remove the conflict markers, then stage and commit the result. VS Code makes this
especially easy with its built-in merge editor that shows both versions side by side.
GitHub and Remote Repositories
Creating a Repository on GitHub
- Sign in at github.com
- Click "New repository"
- Name your repo and choose Public or Private
- Do not initialize with a README if you already have a local project
- Click "Create repository"
Linking Your Local Project to GitHub and Pushing
git remote add origin https://github.com/username/my-project.git git branch -M main git push -u origin main
The first command tells Git where your remote repository lives, giving it the alias
origin.
The second renames your main branch to
main (the modern standard, replacing the older master). The third
pushes your project to GitHub for the first time.
To push a specific branch (for example, a staging branch):
git checkout staging git push origin staging
git push. You'll need to authenticate with a
Personal Access Token (PAT) — generate one at
GitHub → Settings → Developer settings → Personal access tokens. Alternatively, you
can set up SSH keys for passwordless authentication, which is the preferred
approach for daily development work.
Cloning an Existing Repository
Found a project on GitHub you want to work with — your own, a teammate's, or an open-source
repo? Use git clone:
git clone https://github.com/username/project-name.git
This downloads the entire project — including its complete commit history and the
.git folder — and sets up the remote automatically. No need to run
git init or configure anything manually.
Clone vs. Fetch vs. Pull — What's the Difference?
| Command | What it does | When to use it |
|---|---|---|
git clone |
Downloads a full copy of a remote repo to your machine | First time you want to work on a project |
git fetch |
Downloads remote changes without merging them | When you want to review changes before merging |
git pull |
Downloads AND immediately merges remote changes (fetch + merge) | Daily sync with your team's shared repository |
A GitHub repository — where your team's code converges in one place
How to Undo Mistakes in Git — You've Got More Options Than You Think
This is the section most beginner guides skip — which is a shame, because knowing how to safely undo things is what gives you the confidence to experiment freely. Git was specifically designed to make mistakes recoverable.
Discard Working Directory Changes — git restore
git restore index.html # Undo changes in one file git restore . # Undo all uncommitted changes
Warning: this is permanent — the changes are gone from your Working Directory with no recovery. Only use this when you're sure you want to discard those changes.
Temporarily Shelve Work — git stash
Imagine you're mid-feature and your lead sends a Slack message: "Can you fix this urgent bug
right now?" You're not ready to commit your current work. git stash saves it to
a temporary drawer so you can switch branches cleanly:
git stash # Save current work temporarily git stash pop # Restore it when you're back git stash list # See all stashed states
Fix Your Last Commit — git commit --amend
Forgot to include a file? Typo in your commit message? Fix it without creating a new commit:
git commit --amend -m "Your corrected message here"
Safely Reverse a Pushed Commit — git revert
If a commit has already been pushed to GitHub and shared with your team,
git revert is the safe option. It creates a new commit that undoes the changes
from a specific commit — without rewriting history:
git revert abc1234 # Use the commit hash from git log
Undo Commits Locally — git reset (Use with Caution)
git reset moves your branch pointer back to an earlier commit. The
--hard flag wipes out all changes permanently; without it, the changes remain in
your Working Directory for you to re-edit:
git reset HEAD~ # Undo last commit, keep changes in Working Directory git reset --hard HEAD~ # Undo last commit AND discard all changes permanently
Time Travel — git checkout <commit-id>
Sometimes you don't want to undo anything — you just want to look at how the code was at a
specific point in the past. Grab a commit hash from git log and use:
git checkout abc1234
This puts you in a Detached HEAD state — you can browse and even run the code
exactly as it was at that moment. Nothing is changed. When you're done exploring, return to the
present with git checkout main.
Pull Requests — How Developers Collaborate on GitHub
A Pull Request (PR) is GitHub's collaboration mechanism. When you finish work
on a feature branch, you don't merge it directly into main — you open a PR so
your teammates can review the code, leave comments, request changes, and ultimately approve
the merge.
In my experience working with professional teams, no code reaches the production branch without going through a PR. It's the single most effective quality gate in modern software development.
Steps to Open a Pull Request
- Push your branch to GitHub:
git push origin feature-auth - On GitHub, click "Compare & pull request"
- Write a clear description of what you changed and why
- Assign reviewers from your team
- Address any feedback they leave — update your branch and push again
- Once approved, the PR gets merged into
main
git rebase — For a Cleaner, Linear Project History
git rebase is a slightly more advanced topic, but worth understanding early.
Instead of creating a merge commit that shows "Branch A merged into Branch B," rebase replays
your branch's commits on top of the latest state of
main — as if your feature was built on top of the most recent code from the start.
The result is a cleaner, linear history with no merge commits:
git checkout feature-auth git rebase main
Advanced Tips That Will Make Your Daily Git Life Easier
1. Use VS Code's Built-in Git GUI
While understanding the command line is non-negotiable, VS Code's Source Control panel (the branch icon in the left sidebar) gives you a clean visual interface for staging, committing, and resolving conflicts. I use both: the command line for complex operations, VS Code's GUI for quick daily staging and commit work.
2. Host Your Portfolio for Free with GitHub Pages
One of GitHub's most underrated features for beginners: push any HTML/CSS/JS project to a repository, enable GitHub Pages in the repo's Settings, and you instantly get a live, publicly accessible URL you can share with anyone — including potential employers. It's completely free.
3. Write a Great README.md
Your README.md is the front page of your GitHub repository. Written in
Markdown, it's what visitors read first. A well-written README — with a
project description, setup instructions, and usage examples — can be the difference between
someone using your project or moving on. It's worth learning
Markdown syntax thoroughly if you haven't already.
4. Create Git Aliases for Speed
You'll type the same commands hundreds of times a week. Aliases let you shorten them:
git config --global alias.st status git config --global alias.co checkout git config --global alias.lg "log --oneline --graph" # Now you can type: git st # instead of: git status git co main # instead of: git checkout main git lg # instead of: git log --oneline --graph
Git Command Cheat Sheet — The Complete Quick Reference
Understanding Git isn't about memorizing commands — it's about internalizing the Working → Staging → Commit → Push workflow. Once that mental model clicks, everything else follows naturally. Here's a complete reference of everything covered in this guide:
| Command | What It Does |
|---|---|
git init |
Start tracking a folder with Git |
git clone [url] |
Download a repository from GitHub |
git status |
Show the current state of your files |
git add . |
Stage all modified files |
git rm [file] |
Delete a file and stage the deletion |
git diff |
Compare changes between two commits |
git commit -m "msg" |
Permanently save staged changes with a message |
git push |
Upload local commits to GitHub |
git pull |
Fetch and merge remote changes |
git branch [name] |
Create a new branch |
git merge [name] |
Merge a branch into the current branch |
git stash |
Temporarily shelve uncommitted work |
git revert [hash] |
Safely reverse a commit without rewriting history |
Your next step: create a real project on GitHub right now — even if it's just a simple HTML page. Hands-on practice is what makes Git stick. If you want to go deeper on the programming side, check out our guide on how to learn programming as a beginner, and if you're exploring database options for your projects, our comparison of MySQL vs. PostgreSQL vs. SQLite is a natural next read.
Found This Guide Helpful?
Join hundreds of subscribers and get the latest tutorials and guides delivered straight to your inbox.
Yes, Subscribe Me! ✉️🔒 No spam, ever. Unsubscribe anytime.
We'd love to hear your thoughts! Leave a comment below
and share your experience or questions.