Learn Git, GitHub &
VS Code Source Control
A visual, hands-on guide for any student or first-time coder: track changes, save meaningful checkpoints, publish projects to GitHub, and work confidently in VS Code.
By Avijit Roy · Updated
What Is Version Control?
Picture this: you have been building your first program or website for hours. You finally get it working, try one more improvement, and suddenly nothing works. This is the problem that version control was built to solve.
Think of version control as an undo history for your whole project, with checkpoints you choose to save. If a new change breaks your program, you can look back at an earlier checkpoint and recover the version that worked. In Git, saving one of these checkpoints is called making a commit. Saving a file in your editor updates the file; making a commit records a checkpoint in Git. Git cannot recover an edit it never recorded just because you pressed Save.
The Problem Without Version Control
Without version control, beginners commonly fall into patterns like these:
- Saving files as
project_final.py,project_final2.py,project_FINAL_v3_actually.py - Accidentally overwriting working code with broken experiments
- Having no way to tell what changed between two versions
- Sharing code through email or USB drives — a collaboration nightmare
Why It Matters for Every New Coder
Whether you are completing a class project, making a portfolio website, analyzing data, or contributing to an open-source project, your work will grow and change. Version control lets you experiment safely, restore known-working versions, share your progress, and build the workflow expected in software teams.
Understanding Git
Git is a free, open-source version control system created by Linus Torvalds in 2005, who also created the Linux kernel. Git can keep project history on each person's computer and exchange checkpoints between copies; this is what distributed means. Local tasks such as committing, branching, and viewing downloaded history work without internet access. A remote is another repository Git can exchange history with, such as a copy on GitHub. Reaching GitHub requires a network connection.
Think of a repository, or "repo," as your project plus its Git history. In a typical local project, git init creates a hidden folder named .git to keep that history and Git's settings. The files you open and edit are called the working tree. Git records the checkpoints you commit, rather than automatically recording every file save.
Core Concepts
Three Zones You Must Know
| Zone | Description | Relevant Command |
|---|---|---|
| Working Directory | Where you edit files. New files are untracked until staged; edits to tracked files are modifications. | — |
| Staging Area (Index) | The selection for your next checkpoint. Like choosing photos for an album, you choose the versions to include. Later edits need staging again. | git add filename |
| Repository | Your saved checkpoints and Git's settings. Each commit records the staged version and has an ID you can use to find it. | git commit -m "message" |
git commit, unstaged edits are left out. If there are no staged changes, Git normally refuses to create a commit. Save your file, stage the intended version with git add, and review it with git diff --staged. If you edit it again after staging, stage it again to include those newer edits.
Understanding GitHub
GitHub is an online hosting and collaboration platform for Git repositories. When you push a local Git repository to GitHub, you create an online copy you can access from another computer and share with teammates, teachers, reviewers, or future employers when appropriate.
GitHub adds a social and collaborative layer on top of Git. You can browse code, open issues (like bug reports), review changes before they're merged, and contribute to projects happening anywhere in the world — including the open-source software that powers most of what you use daily.
What GitHub Adds
- Remote hosting — pushed commits are stored online. Uncommitted files and local commits you have not pushed remain on your machine.
- Pull Requests (PRs) — a formal way to propose code changes and request review before merging.
- Issues & Project Boards — built-in task tracking. You can file bug reports, feature requests, and track what's in progress.
- GitHub Actions — workflows you configure to run tests, build code, or deploy an app on events such as pushes or pull requests.
- GitHub Pages — static website hosting from a repository; availability depends on your plan and repository visibility.
- GitHub Codespaces — a hosted development environment accessible through your browser or VS Code, subject to usage limits and billing.
Git vs GitHub — The Clear Distinction
This is probably the most common source of confusion for beginners, and it's worth making the distinction crystal clear before going further.
- Software installed on your computer
- Local commits and history work offline
- Free and open-source (GPLv2-licensed)
- Manages version history locally
- No account or login required
- Command-line tool with many graphical clients
- Created by Linus Torvalds, 2005
- A website and cloud service
- Requires internet access
- Free public and private repos; features vary by plan
- Hosts Git repositories online
- Public repositories can be read without an account
- An account is needed to publish or contribute
- Has a full web interface + features
- Founded 2008; acquired by Microsoft 2018
| Aspect | Git | GitHub |
|---|---|---|
| Type | Software (CLI tool) | Web platform / service |
| Internet required? | No for local tasks; yes to contact an online remote | Yes |
| Main purpose | Track changes locally | Share, collaborate, backup |
| Collaboration | Built-in branches, merges, and exchange of commits | Core feature (PRs, Issues, Forks) |
| Storage location | Your machine | The cloud |
| Learning curve | Steeper (command-line) | Gentler (visual UI + CLI) |
| Can exist without the other? | Yes — Git works standalone | You can use GitHub's browser tools without a local Git installation |
Essential Commands
You can control Git from a terminal (PowerShell, Terminal, Git Bash, or another shell) or through VS Code. Learning the small command-line vocabulary below makes every visual tool easier to understand.
Install and Set Up Git Once
Install a current Git version from git-scm.com, then configure the name and email recorded in your commits. These are author details, not GitHub sign-in credentials. The git init -b examples require Git 2.28 or later.
noreply address from GitHub's email settings and use it in git config --global user.email before committing. Changing this setting does not rewrite earlier commits.
$ prompt or sample output. PowerShell has different shell syntax and file encodings; you can create and save the files in VS Code and run the Git commands separately. Replace example usernames, repository names, and filenames with your own. Your commit IDs and output may differ from the examples.
Starting a Repository
# OR clone an existing repo from GitHub git clone https://github.com/username/repo-name.git
The Daily Loop — Add, Commit, Push
After editing and saving files, stage the intended changes, commit locally, and push when ready to share them. This example assumes a tracked main.py, a current branch named main, and a writable remote named origin. The first-push setup follows below.
# Step 1: Stage the files you want to commit git add main.py # Alternative: stage additions, edits, and deletions under this directory git add .
# Step 2: Commit with a clear, descriptive message git commit -m "Add user input validation to main.py" [main 3f4a1c2] Add user input validation to main.py 1 file changed, 12 insertions(+), 2 deletions(-)
# Step 3: Push to GitHub (sync to remote) git push origin main Enumerating objects: 5, done. To https://github.com/username/my-project.git
Stage means "select for the next checkpoint." Staging does not move your original files. git add . selects eligible new files, edits, and deletions in the current folder and its subfolders; it skips ignored new files. Review that selection before committing. git push origin main uploads the saved history of the branch named main, even if you are currently working on another branch.
First Push from a New Local Repository
After making a local commit, create an empty repository on GitHub and choose its visibility. For this path, leave the README, license, and .gitignore initialization options off, because your local repository already has its own history. If you started by cloning a GitHub repository, origin is already configured; skip git remote add.
A remote is another repository whose address Git remembers, often your copy on GitHub. Think of origin as a contact name for that address; it can point to GitHub or another host. -u sets an upstream: the remote branch paired with your local branch for later pushes and pulls. If your branch has a different name, use that name consistently. See GitHub's first-push instructions.
Viewing History & Differences
# See what changed in your files (not yet staged) git diff # See what's staged but not yet committed git diff --staged
Pulling Changes From GitHub
Commit your intended work before pulling, and use git status to check that your working tree is clean: there are no pending changes to commit. Ignored files can still be present.
Think of git fetch as bringing new checkpoints home so you can inspect them: it downloads remote history and updates Git's record of the remote branches, without changing your working files. git pull fetches and then brings a remote branch's changes into the branch you are currently working on. A fast-forward simply moves your branch to a newer checkpoint on the same path. If you and a teammate both added separate checkpoints, --ff-only stops so you can decide how to combine the two paths.
A merge brings changes from two paths together. Another method, rebase, replays your committed changes on a different starting checkpoint, usually creating replacement commits. Follow your team's chosen method; plain git pull behavior depends on settings, options, and Git version. The branching section below walks through a merge; Git's rebasing guide explains the alternative and its precautions.
Try It: Animated Demo
Click Run Demo to watch a simulated first project move through the four stages. The demo displays example commands and output; it does not run Git or create a repository. The highlighted label shows where each command fits in the workflow.
Ready: create a file, stage it, commit it, then push it to GitHub.
Command Reference
| Command | What It Does |
|---|---|
git init | Initialize a new Git repository in the current folder |
git clone <url> | Create a local copy of a repository from a URL or local path |
git status | See which files have changed and what's staged |
git add <file> | Stage that file's current contents (or its deletion) |
git commit -m "msg" | Save staged changes as a commit with a message |
git push origin main | Push local main to main on the remote named origin |
git fetch origin | Download commits and update remote-tracking references |
git pull --ff-only origin main | Fetch remote main and fast-forward the current branch, or stop if histories diverged |
git log --oneline | View the compact commit history |
git diff | Compare tracked working-tree contents with the index; untracked file contents are not shown |
git diff --staged | Compare the staged snapshot with the last commit |
git restore --staged <file> | Unstage a file using the last commit; keep its working copy |
git restore <file> | Replace a tracked file's working contents with the index version; unstaged edits are lost |
VS Code Source Control: A Visual Way to Use Git
VS Code includes Git integration in its Source Control view and uses your installed Git for local repositories. Install Git and configure your name and email first. Open Source Control with Ctrl+Shift+G (Control+Shift+G on macOS as well). The editor and terminal use the same repository.
Your First Commit in VS Code
VS Code Buttons and Their Git Meaning
| VS Code Action | Git Equivalent | Purpose |
|---|---|---|
| Initialize Repository | git init | Begin tracking this folder. |
| + beside a changed file | git add filename | Select that change for the next checkpoint. |
| Commit | git commit -m "message" | Save staged changes locally. |
| Publish Branch / Push | git push -u / git push | Upload a branch and set its upstream when publishing. |
| Pull | git pull | Fetch and integrate changes into the current branch. |
| Sync Changes | git pull, then git push | Bring in remote work before uploading local commits. |
| Branch indicator | git branch / git switch | See or change your current line of work. |
Publish a New Folder to GitHub
- Make one local commit first so the repository has something meaningful to publish.
- For a repository with no remote, select Publish to GitHub in VS Code and sign in when asked. The status-bar Publish Branch action can offer this path when no remote exists.
- Choose visibility deliberately: keep private work private unless you intend to share it publicly.
- Open the new repository on GitHub and check that your files and commit history are present.
See the official VS Code source-control quickstart. Available labels and actions can vary with repository state and settings.
Real-World Workflow
Knowing individual commands is one thing. Understanding how they fit into a coherent workflow is what separates someone who "knows Git" from someone who can actually use it productively on a team.
Your Personal Project Workflow
For an assignment, portfolio project, experiment, or learning exercise, this sequence covers the daily essentials:
git clone https://github.com/you/repo.git creates a local checkout and configures origin. Then enter it with cd repo or open that folder in VS Code.When Other People Contribute
For team projects, update main with a clean working tree before creating a feature branch. Work and commit on that branch, push it with git push -u origin feature/add-login, and open a pull request. Pulling updates the branch you have checked out; it does not automatically update every branch. Bring newer main changes into a feature branch using your team's merge or rebase policy.
Writing Good Commit Messages
Your commit message is a note to your future self (and your teammates). Here's how to write ones that actually help:
✅ Good commit messages — tells a story git commit -m "Add input validation for user age field" git commit -m "Fix index out of bounds in search function" git commit -m "Refactor printReceipt to reduce code duplication"
Branching & Merging
Imagine trying a new idea on a side path from a saved checkpoint. That is what a branch lets you do: build a separate line of history while the original branch keeps its saved version. Technically, a branch is a name pointing to a commit; creating one does not duplicate the whole project. Switching branches usually updates the files in your working folder to the chosen branch's version.
The initial branch name depends on your Git configuration or the host's settings. This guide uses main, selected explicitly with git init -b main; other repositories may use master or another name. Create a feature branch, a branch for a particular change, and commit there. When ready, merge it to bring its changes into the project's shared branch. A branch named main is a convention, not a guarantee that the code works.
The diagram shows a merge commit after both branches advanced. If main has not advanced since the feature branch started, Git can usually fast-forward it to the feature's latest commit without creating a merge commit.
Branch Commands
# Create and immediately switch to a new branch git switch -c feature/add-login Switched to a new branch 'feature/add-login'
# Create and save login.py in your editor, then commit it git add login.py git commit -m "Implement basic login function"
# Switch back to main git switch main
# Merge the feature branch into main git merge feature/add-login Updating a1b2c3d..e4f5a6b Fast-forward login.py | 1 + 1 file changed, 1 insertion(+)
# Clean up — delete the local branch after merging git branch -d feature/add-login
HEAD as Git's "you are here" bookmark. It usually names your current branch, which points to its latest checkpoint. A new commit advances that branch; switching branches changes where the bookmark points. Opening an older commit directly can put you in detached HEAD: the bookmark points to that commit instead of a branch.
When a Merge Conflict Happens
Git may pause when it cannot combine changes automatically, such as conflicting edits to the same lines or an edit on one side and deletion on the other. VS Code provides inline actions and a merge editor for text conflicts. Edit the result deliberately, remove conflict markers, test the result, and stage every resolved file before completing this merge with a commit. Use git status to see what remains; git merge --abort cancels an in-progress merge.
# After editing the file to the correct final text: git add index.html git commit -m "Resolve homepage heading conflict"
Protect Your Project with .gitignore
A .gitignore file specifies patterns for untracked files Git should ignore during ordinary staging. It does not stop tracking files already in the index. Create it early and commit the file to share the patterns with teammates; a user can still force-add an ignored file, so these rules are not access controls.
.env file may contain credentials. Public repositories can be copied quickly, and deleting a secret later does not make an exposed credential safe again.
What .gitignore Does and Does Not Do
| It Helps With | It Does Not Do |
|---|---|
| Preventing new matching files from being staged accidentally. | Removing a file already committed or pushed to GitHub. |
| Keeping dependencies, generated builds, and local settings out of history. | Encrypting files or making the folder private on your computer. |
Sharing a repository rule with teammates through a committed .gitignore. |
Guaranteeing that editors, extensions, or AI tools cannot read ignored files. |
A Beginner-Friendly Starter File
Use patterns appropriate to your project. Keep a safe example configuration file, such as .env.example, with placeholder values so other people know what settings they need.
# Dependencies, virtual environments, and generated output node_modules/ .venv/ __pycache__/ dist/ build/
# Local operating system clutter .DS_Store Thumbs.db Desktop.ini
Check Before Every Commit and Push
git rm --cached .env leaves the local file on disk and stages its removal from the tracked snapshot. Commit that removal along with the ignore rule. Earlier commits still contain it. git check-ignore normally skips tracked files, and a diff may not show binary file contents; inspect the staged filenames as well as the diff.
.gitignore alone is not a fix.
For the official procedures, read GitHub's Ignoring files guide and Removing sensitive data from a repository guide.
Safe AI-Assisted Coding Workflow
AI tools can explain code, suggest tests, and help debug, but they also process the files or text you allow them to see. Use AI as a coding partner only after you have decided which information is safe to share.
.gitignore excludes matching untracked files from ordinary Git staging. It does not prevent an AI tool from reading them. An exclusion setting may control indexing or suggestions without restricting filesystem access; check the tool's actual capabilities and permissions.
Set Boundaries for AI Tools
- Create
.gitignorebefore asking an assistant to build or publish a project. - Keep real keys in ignored local files or a secret manager; give the assistant a placeholder-only
.env.example. - Use the tool's supported exclusions and permissions. If it must not read sensitive files, keep those files outside its accessible workspace or enforce filesystem restrictions; an ignore pattern or written instruction alone is not an access boundary.
- State the rule directly in your request: do not open, quote, edit, stage, or commit secret-bearing files.
- Before committing AI-generated changes, review the diff yourself and run the Git privacy checks from the previous section.
When You Intentionally Need an Ignored File
An ignored file is not automatically unsafe. Generated logs, test output, or large local data may be ignored simply because they do not belong in Git history. If an AI tool needs information from one of these files, provide a small sanitized excerpt or explicitly allow only the non-sensitive path. Do not tell an assistant to ignore every .gitignore rule across the workspace, and never override ignore rules for a secret just to make an AI workflow easier.
Fix Common Beginner Problems
When Git reports a problem, do not delete the repository and start over. Read git status first: it usually names the state you need to fix.
| What You See | What It Means | First Safe Step |
|---|---|---|
fatal: not a git repository |
The terminal is in the wrong folder, or Git was never initialized there. | Open the correct project folder; use git init only for a new repository. |
nothing to commit or no changes added to commit |
There is no new staged snapshot to commit. The working tree may be clean, or edits may be unstaged or ignored. | Save your file and inspect git status. Stage the intended changes if there are any. |
Push rejected as non-fast-forward |
The remote branch contains history your local branch does not include. | Fetch and inspect the correct branch. Try git pull --ff-only with its upstream configured; if histories diverged, follow the team's merge or rebase policy. Do not force-push as a routine fix. |
| Authentication or permission error while pushing | Credentials, repository access, or a branch rule may prevent the push. | Check the remote URL, sign-in method, write access, and any requirement to submit a pull request. Pulling does not fix permission errors. |
| Wrong file is staged | The file is selected for the next commit, but no work is lost. | After an initial commit, use git restore --staged filename. Before the first commit, use git rm --cached -- filename for a newly staged file. Both leave the working file on disk. |
| Secret or generated file appears in Changes | The file should probably not be recorded in history. | Add an ignore pattern for an untracked file. If it is already tracked or staged, also remove it from the index with git rm --cached. Rotate exposed credentials and assess history cleanup. |
git restore --staged filename changes the index and keeps your working file. git restore filename replaces a tracked working file with its index version, discarding unstaged edits. Check the diff and save any work you need before discarding it.
.gitignore file prevents untracked files such as .env and build output from being added accidentally; it cannot erase a secret already committed and shared.
# Review what Git will include before committing git status git diff --staged
Practice Lab: Publish Your First Repository
Build a small repository with four meaningful commits, starting with an ignore rule that protects local secrets. Complete it with the terminal, with VS Code Source Control, or by switching between both views so you see that they describe the same Git history.
git-practice-lab, initialize Git, and add a .gitignore before making project files..gitignore, README.md, learning notes, and a README update describing what you practiced.echo "Things I learned about Git" > notes.txt git add notes.txt git commit -m "Add learning notes" echo "## What I Practiced" >> README.md git add README.md git commit -m "Document practice steps" git log --oneline
Knowledge Check
Answer these 14 questions to test your understanding. Click any option to see whether you got it right and why.
Documentation and Practice Resources
This tutorial covers the essentials, but mastery takes practice and deeper reading. Use the official Git, GitHub, and VS Code documentation to verify commands and behavior. The extended ebook and third-party practice resources provide additional learning material.
Keep This Guide Handy
Save or Install the Tutorial
Keep this one-page guide easy to reopen while you practice. Installation opens it like an app on supported devices; a bookmark is another option. Once the offline cache is ready, supported browsers can reopen the guide without a connection. External resources still need internet access, and browsers may clear cached data.
Select the button for the installation steps supported by your browser.
Save it on your device:
- Windows / Linux: press
Ctrl+Dto bookmark it. - Mac: press
Command+Dto bookmark it. - iPhone / iPad Safari: select Share, then Add to Home Screen.
- Android or desktop browsers: use Install or Add to Home screen from the browser menu when available.
Continue Learning
Core Documentation
Interactive Learning
Accuracy review: . Specific references: tracking and staging, pull behavior, branches and HEAD, ignore rules, and restore and unstage.