Git & GitHub - Save, Track & Share Code

Introduction:

Have you ever worked on a project and wished you could go back to an earlier version? Or maybe you wanted to share your code with others easily? That’s where Git and GitHub come in!

In this blog, we’ll walk through the basics of what Git and GitHub are, how they help you save your work step-by-step, and how you can safely share your projects online and how to manage your code files history. Don’t worry β€” no fancy tech jargon here. Just clear, simple explanations to get you started.

πŸ“˜ What is a Version Control System (VCS)?

Imagine you're writing code on your own computer. Over time, you might add new features, fix bugs, or even accidentally break something that used to work. So how do you keep track of all these changes? How do you go back to the previous version if needed?

That’s where a Version Control System (VCS) comes in.

A VCS is like a smart record keeper for your code. It keeps track of every change you make β€” whether you're adding a new file, updating old ones, or deleting something. You can think of it like a time machine for your project.

e.g. : Git, Subversion, Mercurial, Perforce

What is Git?

Git is a tool that helps you keep track of changes you make to your files β€” like saving different copies of your project as you work on it. It’s especially helpful when you're working with a team so that everyone can edit files without messing up each other’s work.

Here’s how it usually works in a team:

  • πŸ”€ Start a Branch
    You create your own copy (called a branch) from the main project, so you can work on it without affecting the original files (main branch).

  • ✍️ Make Your Changes
    You edit and update the files on your branch β€” it’s like having your own personal workspace.

  • πŸ” Bring It All Together
    Once you’re done, Git helps combine (or β€œmerge”) your changes back into the main project (main branch), making sure nothing breaks or overlaps with your teammates’ updates.

  • 🧠 Tracks Everything
    Git keeps a full history of who changed what, so the whole team is always working on the latest copy and nothing gets lost.

πŸ› οΈ Install Git – Quick Guide

πŸͺŸ Windows

  1. Go to git-scm.com

  2. Download the Git for Windows installer (e.g.: Git for Windows/x64 Setup)

  3. Run the setup and follow the default options

βœ… To check:

  • Open Command Prompt and run

      git --version
    

🍎 macOS

Option 1 (easiest):

  • Open Terminal and type:

      git
    
  • It will prompt you to install Xcode Command Line Tools (includes Git).

Option 2 (with Homebrew):

brew install git

βœ… To check:

git --version

🐧 Linux (Ubuntu/Debian)

  • Open Terminal and run:

      sudo apt update  
      sudo apt install git
    

βœ… To check:

git --version

🌐 What is GitHub?

GitHub is a web-based hosting service for Git repositories. GitHub is an online platform where you can store, share, and collaborate on code with others.

πŸ” Why use GitHub?

Storing your project in a repository on GitHub allows you to:

  • πŸ“‚ Keep your code safe in the cloud

  • πŸ‘€ Share your work with others or showcase it publicly

  • πŸ•’ Track changes made to your code over time

  • πŸ§‘β€πŸ’» Collaborate easily with others without overwriting each other’s work

  • πŸ’¬ Get feedback and suggestions from other developers

πŸ“ What is a Repository?

A repository (or repo) is like a folder where your project lives. It stores all your code files, along with a history of the changes you make over time.

πŸ§‘β€πŸ’» How to Create a GitHub Account

  1. Go to github.com

  2. Click on β€œSign up” (top right corner)

  3. Enter your:

    • Username

    • Email address

    • Password

  4. Follow the steps to verify your email and complete the setup.

  5. You’re in! πŸŽ‰ Now you can create your first repository and start sharing code.

Your config settings:

Before you start using Git, you need to tell it who you are.

After GitHub account is created then use the email and username.

πŸ”§ Step 1: Open your terminal or command prompt

Then run these two commands with your name and email:

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

Example:

git config --global user.name "John Doe"
git config --global user.email "johndoe@gmail.com"

βœ… Step 2: Check your settings

git config --list

If your name and email show up, you’re all set!

Git Basic Commands:

To use Git, you can use these commands directly in the command line, or through tools like GitHub Desktop or right inside code editors like VS Code, Atom, Sublime Text, JetBrains IDEs like WebStorm, PyCharm, and IntelliJ IDEA, which provide a more visual experience.

You don’t need to memorize every commandβ€”just get comfortable with the basics and you’ll build confidence as you go.

πŸ“ 1. Start a Local Git Project(folder)

git init

βœ… Use this when you're starting a new project and want Git to track it.

Use terminal to create folder or new directory or manually create folder on the file explorer.

mkdir my-project
cd my-project
git init
#example
mkdir bigin-git
cd bigin-git
git init

The above commands for creating in your terminal. But you can create directly in your code editor also.

.git folder:

When you run git init, Git creates a hidden folder called .git inside your project directory. This .git folder is like Git’s brain β€” it stores all the information Git needs to track changes, manage commits(snapshots), and handle commits, branches, and remotes.

Tip: Don't delete or edit this folder manually β€” it's essential for Git to work properly.

πŸ“„ 2. Check the status of your repo(repository):

git status

Shows the current state of your files (what's changed, what's staged).

βœ… Run this often to see what Git is tracking.

git status

πŸ“„ 3. Add Some Files

Create or copy your files (like index.html, style.css, etc.) inside the folder.

πŸ”„4**. Track and Stage**

Untrack File:

Then track the file use the below command;

git add

Adds changes to the "staging area" (preparing them to be saved).

πŸ“‚ Staging = preparing your files for a snapshot.

βœ… Use this to tell Git which files you want to save.

git add filename.txt
# or add all files
git add .

Tracked

πŸ’Ύ 5. Save Changes

git commit

Saves your staged changes with a message.

βœ… Commits are like snapshots of your project at a point in time.

git commit -m "Added login feature"

πŸ•“ 6. View Commit History with Git Log

# See the list of previous commits
git log
#for viewing one line history of commits
git log --oneline

This shows you a timeline of changes β€” who made what change and when.
It helps track the project’s progress and debug if needed.

☁️ 7. Create a Remote Repository

Go to GitHub.com, log in, and click β€œNew Repository.”

Click on dropdown

Click on New repository

Give it a name (like learning-git)

Give a repo name and click on Create repository

πŸ”— 8. Connect Local to Remote

git remote add origin https://github.com/your-username/my-project.git
#example
git remote add origin https://github.com/MrutyunjayaSahoo/learning-git.git

Now your local project is connected to the GitHub repo.

πŸš€ 9. Push Code to GitHub

βœ… Use this to upload your work online or to a shared repo.

git push -u origin main

This sends your code to GitHub. -u sets the default remote so next time you can just use git push.

You’ll see this error because your local branch is named master, but you're trying to push to the main branch on GitHub. Since GitHub sets the default branch as main, you need to rename your local master branch to main to match it.

Here’s a quick fix:

πŸ”„ Rename Your Local Branch to main

# Rename the local branch
git branch -m master main

# Link your local main to the remote main
git push -u origin main

πŸ”„ 10. Make More Changes Locally

# Edit some files
git add .
git commit -m "Updated homepage layout"
git push

Now your updates are saved and shared again.

πŸ§‘β€πŸ€β€πŸ§‘ Collaborating with a Team Using Git:

In a Git repository, multiple developers can’t commit to the same branch at the exact same timeβ€”it may cause conflicts. To avoid this, Git provides a branching systemβ€”each developer can create their own branch to make changes, commit, and push independently. Once their work is complete, it can be safely merged back into the main branch.

🌱 Step 1: Fork the Repository on GitHub

πŸ”— Go to the project repo on GitHub β†’ click Fork (top right).
You’ll now have your own copy of the repo in your account.

GitHub itself doesn’t allow you to fork a repo into the same account where the original repo exists. So that use different account

  1. πŸ“₯ Step 2: Clone the Forked Repo

    git clone β€œforked-url”

    πŸ“ Cloning = downloading the full project and its history.

    • Copy the forked repo URL

git clone https://github.com/yourusername/project-name.git
cd project-name

🌿 Step 3: Create a Branch

All branches are created from the main branch. The main branch is present in the production server.

If you want to contribute to a project, it's a good practice to create a branch with a name like:
yourusername/feature-name or yourusername/repo-name

βœ… This helps your team easily recognize:

  • Who created the branch

  • What the branch is for

πŸ” Example:

for feature name
Mrutyunjaya-Sahoo/added-login-form

for repo name

Mrutyunjaya-Sahoo/webdev-cohort-opensource

git branch <branchname>

🌿 Branches let you work safely without affecting the main code.

#To see the list or current branch
git branch
#Create a branch
git branch <yourbranchname>
#example
git branch MrutyunjayaSahoo/Login-Form

πŸ”€Step 4: Switch to created branch

git checkout <branchname>

Switches between branches or files.

βœ… Move to a different branch or restore a previous version of a file.

git checkout <branchname>
#example
git checkout MrutyunjayaSahoo/Login-Form

πŸ“„Step 5: Create a file

Once you've created your branch when contributing to a Git project.

πŸ› οΈ Step 6: Make Changes Locally

Edit code, save your files.

βœ… Step 7: Add & Commit

πŸ“ Snapshot your work before sharing it.

git add .
git commit -m "Added Login Form"

πŸ“€ Step 8: Push to Your Fork

git push
  • You're seeing this error because Git doesn't yet know where to push your newly created branch. This happens when you create a new branch locally but haven't told Git which remote branch to track for pushing.

❌ Error:

βœ… Solution:

You need to tell Git to both push and set the remote branch for the first time like this:

πŸ“¦ Send your changes to your forked repo on GitHub.

πŸ” Step 8: Open a Pull Request (PR)

  • Go to your forked repo on GitHub

  • Click Compare & Pull Request

  • Write a message and click Create Pull Request

πŸ’¬ A pull request tells the original team: β€œHere are my changes, please review and merge them.”

πŸ”„ Merge:

Use git merge after your branch is reviewed and approved:

Make sure you are in a remote repo to see the branches and merged commits.

In a team workflow, all new branches are created from the main branch. The main branch typically represents the live or production version of the project.

You can’t merge directly to main Instead:

  • Create your own branch.

  • Push changes and open a Pull Request.

  • Once reviewed and approved by the team, it gets merged into main.

  • After merge, changes are automatically deployed to production.

In every merging, always switch to the main branch then you can merge your branch to main branch.

This keeps the main branch clean and safe! πŸš€

git branch <branchname>
git checkout <branchname>
git branch
#example
git branch frontend
git checkout frontend
git branch

Now create a folder or file:

I have created a folder named β€œfrontend” because I want to add more features like about us, contact us to the same branch i.e. frontend.

βž• Add and Commit Your Work

After adding your files:

git add .                # Stage all your changes
git commit -m "Added about and contact us pages"

This saves your changes only in the frontend branch.

πŸ”„ Go Back to Main Branch

Now, if you switch back to the main branch:

git checkout main

You’ll notice the frontend folder and files are gone! Don’t worry β€” they’re still safe in the frontend branch.

πŸ”— Merge Your Work Into Main

Once your work in the frontend branch is complete and ready:

git merge frontend

Now, all the files and folders you added in the frontend branch will be merged into the main branch and become part of your main project. βœ…

As you can see there are two branches and commits of new branch;

Merge Workflow:

🧹Squash Merge:

git merge --squash β€” Clean and Combine Your Commits

When you've made lots of small commits in your feature branch but want to combine them into one single commit before merging to the main branch, you can use:

git merge --squash <branch-name>

βœ… Why Use --squash?

  • Keeps your main branch clean and readable.

  • Combines all changes from a branch into one neat commit.

  • Helpful when your commit history is messy (like 10 commits just fixing typos πŸ˜…).


πŸ”„ Example Workflow

Let’s say you are on the main branch and want to merge the frontend branch cleanly:

git checkout main
git merge --squash frontend
git commit -m "Added frontend features (about, contact pages)"
  • This collects all the changes from the frontend branch,

  • And lets you create one final commit manually.

Note: The frontend branch history won't come with the merge β€” just the changes.

Squash Merge Workflow:

πŸ” What is Git Rebase?

git rebase is used to rewrite the commit history in a cleaner, linear way.

When multiple developers are working on the same branch, some may finish their features earlier while others take more time. If everyone merges directly into the main branch, the commit history becomes messy and hard to follow.

Instead of merging, you can use:

git rebase main

This moves your branch to the latest point of the main branch, replaying your commits one by one on top of it β€” keeping the history clean and linear.


πŸ’‘ Example Scenario:

  • Developer A creates feature-a and finishes work quickly.

  • Developer B creates feature-b but takes longer to complete it.

  • Meanwhile, feature-a is already merged into main.

Now Developer B’s history is outdated compared to main.

So before merging, Developer B runs:

git checkout feature-b
git rebase main

This takes B’s commits and reapplies them on top of the updated main branch, making it look like they were written just now β€” as if everything happened in order.


βœ… Benefits of Rebase:

  • Clean, linear commit history.

  • Easier to read project timeline.

  • Avoids unnecessary merge commits.

Rebase Workflow:

πŸ› οΈ Essential Git Commands Cheat Sheet:

CategoryCommandDescription
πŸ”§ Setupgit config --global user.name "Your Name"Set your name
git config --global user.email "email@example.com"Set your email
git config --global core.editor codeSet VS Code as default editor
git config --listList all Git configs

πŸ“ Repository BasicsCommandDescription
Initgit initInitialize new Git repository
Clonegit clone <url>Clone a remote repository
Statusgit statusCheck status of changes
Loggit logShow commit history
Short Loggit log --oneline --graphView condensed history graph

✍️ Working with CommitsCommandDescription
Addgit add <file>Stage a file
Add Allgit add . or git add -AStage all files
Commitgit commit -m "message"Commit changes
Amendgit commit --amendEdit last commit
Restore Filegit restore <file>Discard changes in file
Reset Filegit reset <file>Unstage a staged file

🌿 BranchesCommandDescription
List Branchesgit branchList local branches
Create Branchgit branch <branchname>Create new branch
Switch Branchgit checkout <branchname>Switch to branch
Rename Branchgit branch -m <newname>Rename current branch
Delete Branchgit branch -d <branchname>Delete branch
Create & Switchgit checkout -b <branchname>Create and switch to new branch

πŸ”€ Merging & RebasingCommandDescription
Mergegit merge <branch>Merge branch into current
Squash Mergegit merge --squash <branch>Merge with squashing commits
Rebasegit rebase <branch>Rebase onto another branch
Abort Rebasegit rebase --abortCancel a rebase
Continue Rebasegit rebase --continueContinue after conflict resolution

πŸ” Undo & HistoryCommandDescription
Revertgit revert <commit>Undo a commit (safe)
Reset Softgit reset --soft <commit>Move HEAD but keep changes staged
Reset Mixedgit reset --mixed <commit>Unstage and keep changes
Reset Hardgit reset --hard <commit>Discard all changes

πŸ“€ Remote OperationsCommandDescription
Add Remotegit remote add origin <url>Link local repo to remote
View Remotesgit remote -vList remote URLs
Pushgit push origin <branch>Push branch to remote
Pullgit pull origin <branch>Pull changes from remote
Fetchgit fetchGet latest commits without merging

πŸ’‘ Stash & TaggingCommandDescription
Stashgit stashSave uncommitted changes
Stash Listgit stash listShow stashes
Stash Applygit stash applyReapply last stash
Taggit tag <tagname>Create a tag
Tag Pushgit push origin <tagname>Push a tag to remote

πŸ“‹ Misc & HelpersCommandDescription
Show Commitgit show <commit>Show specific commit details
Diffgit diffView unstaged changes
Diff Stagedgit diff --stagedView staged changes
Clean Untracked Filesgit clean -fRemove untracked files
Aliasesgit config --global alias.<short>=<command>Create Git aliases

⚑ Git Shortcuts Cheat Sheet:

Full CommandShortcut / Combined VersionDescription
git add . + git commit -m "msg"git commit -am "msg"Add all tracked changes & commit in one step
git branch <branchname> + git checkout <branchname>git checkout -b <branch>Create and switch to new branch (no shorter form)
git statusgst (with alias: git config --global alias.gst status)Show status quickly
git log --oneline --graphgit lg (alias)Compact, graphical commit log
git remote -vgrv (alias)List all remotes verbosely
git branchgb (alias)List all branches
git checkout <branch>gco <branch> (alias)Switch to a branch
git commit --amendgca (alias)Amend the last commit
git reset --hardgrh (alias)Reset completely to previous commit
git fetch --all --prunegfa (alias)Fetch all remotes and clean up deleted branches
git log --onelineglog (alias)Compact commit history
git pull --rebasegpr (alias)Pull with rebase instead of merge
git stash save "msg"gss "msg" (alias)Stash with custom message
git stash apply stash@{n}gsa n (alias with function)Apply specific stash
git diffgd (alias)Show working directory changes
git diff --stagedgds (alias)Show staged changes only
git log --statgls (alias)Commit log with diff stats
git rebase -i HEAD~nβ€”Interactive rebase for last n commits

βœ… How to Set Up Git Aliases:

Use this format to create your own:

git config --global alias.co checkout
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.br branch
git config --global alias.lg "log --oneline --graph --all"

🎯 Final Thoughts:

Git is more than just a tool β€” it's your coding time machine, your collaboration buddy, and your safety net when things go wrong. Whether you're building solo projects or working in a fast-paced team, mastering Git helps you stay organized, work efficiently, and collaborate confidently.

From branching and merging to pushing and pulling β€” every command you’ve learned adds power to your workflow. So keep experimenting, keep committing, and let Git be the silent force behind your development journey.

πŸš€ Code smart. Collaborate better. Git ahead.

20
Subscribe to my newsletter

Read articles from MRUTYUNJAYA SAHOO directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

MRUTYUNJAYA SAHOO
MRUTYUNJAYA SAHOO

Passionate about programming, I see its impact everywhere in the modern world. I believe that I will be a great addition to the team and organization. Making a positive impact through hands-on experience and continuous learning.