Git
Version Control System :-
A Version Control System (VCS) is a tool that helps you track and manage changes to files (usually
source code) over time.
Key Features of a VCS:
Track changes to code and files.
Revert back to earlier versions if needed.
Branching and merging: work on new features or bug fixes without affecting the main code.
Collaboration: multiple people can work together easily.
🚀 Popular VCS Tools:
Git (most popular, distributed)
SVN (Apache Subversion)
Mercurial
Perforce
What is Git?
Git is a distributed version control system used to track changes in source code during software
development.
It allows multiple developers to collaborate, manage different versions of code, and easily roll back if
something goes wrong.
🚀 Why Git?
🧠 Tracks changes in your codebase
👨💻 Enables collaboration between developers
Supports branching & merging (work on features independently)
📦 Keeps full history of your project
🌍 Works with remote repositories like GitHub, GitLab, Bitbucket, etc.
🧱 Git Structure in Simple Terms:
Term Meaning
Repository (Repo) A folder tracked by Git
Commit A snapshot of your changes
Branch A separate line of development
Merge Combining changes from one branch into another
Clone Copying a remote repo to your local machine
Push Sending commits to a remote repo
Pull Fetching and merging changes from remote
Git Setting and Checking
1. Setting Git User Info
Global (applies to all repositories):
git config --global user.name "Your Name"
Local (applies to the current repo only):
git config user.name "Your Name"
2. Checking Git Config Values
Check Global Config:
git config --global user.name
git config --global user.email
Check Local Config (in repo folder):
git config user.name
git config user.email
View All Configurations (global + local + system):
git config –list
Adding file to VCC
What Does git add Do?
git add stages changes in your working directory so they are ready to be committed.
Think of it like: 📝 “I’ve made some changes — these are the ones I want to include in my next
snapshot (commit).”
Why Staging is Useful:
You might not want to commit all changes at once.
You can selectively prepare files for commit.
Basic Usage:
Command What it Does
git add filename Stages a specific file
git add . Stages all changes in the current directory and subdirectories
git add -A Stages all changes including file deletions
git add -u Stages modified and deleted files, but not new ones
git add *.js Stages all .js files in the directory
Example Workflow:
# Make changes to index.html and style.css
git status # See which files changed
git add index.html # Stage only index.html
git status # Now it's staged
git commit -m "Updated index page" # Commit the staged file
Removing file to VCC
To Remove a File from Git (But Keep It Locally)
git rm --cached filename
This unstages and removes the file from Git, but does NOT delete it from your local folder.
Useful for: Removing sensitive files, .env, or files that should be added to .gitignore.
To Remove a File from Git AND Delete It Locally
git rm filename
This removes the file from both Git and your local disk.
After Removing, You Must Commit
After either command:
git commit -m "Removed filename from version control"
Removing a Folder from Git
git rm -r foldername
Add --cached if you want to keep the folder locally but remove from Git.
Ignore File in Future? Add to .gitignore
If you never want Git to track that file again:
1. Add it to .gitignore
2. Then run:
git rm --cached filename
git commit -m "Stop tracking filename"
Git commit
What Does git commit Do?
git commit takes the files you’ve staged (with git add) and creates a snapshot of your code at that
moment.
It’s like:
“Save point created. If I mess up later, I can go back to this state.”
Basic Syntax
git commit -m "Your commit message"
-m stands for "message"
The message should briefly explain what changes you've made.
Some Helpful Flags
Command What it Does
git commit -m "msg" Create a commit with a message
git commit -a -m "msg" Auto-stage modified & deleted files, then commit
git commit --amend Edit the most recent commit (message or content)
git commit (no flags) Opens the default editor to write a longer message
git diff
What Does git diff Do?
git diff shows the line-by-line changes between:
Your working directory and the staging area
OR between commits, branches, or the staging area and last commit
Common Uses:
1. Compare unstaged changes (working directory vs staging area):
git diff
Shows changes you’ve made but not yet staged with git add.
2. Compare staged changes (staging area vs last commit):
git diff –cached
Git Log
git log is a command used in Git to show the commit history of the repository. Here are the details
and options you can use with git log:
🔹 Basic Command:
git log
This shows a list of commits in reverse chronological order, including:
commit hash
author
date
commit message
Useful Options:
1. Show One Line Per Commit
git log –oneline
Shortens commit hash and shows just the commit message.
2. Show Graph of Branches
git log --oneline --graph –all
Visualizes branches and merges in a graph form.
3. Limit Number of Commits
git log -n 5
Shows only the last 5 commits.
4. Show Changes in Each Commit
git log -p
Shows the actual changes (diffs) introduced in each commit.
5. Author-Specific Logs
git log --author="Shyam"
Shows only commits by a specific author.
6. Commits Affecting a File
git log filename.txt
Shows commits where a specific file was modified.
7. Custom Format
git log --pretty=format:"%h - %an, %ar : %s"
Shows concise commit logs:
%h → short hash
%an → author name
%ar → relative date
%s → commit message
git show
The git show command displays detailed information about a specific Git object, most commonly a
commit. It’s like zooming into one commit from git log.
Basic Usage:
git show
Shows the latest commit (on the current branch), including:
Commit hash
Author
Date
Commit message
Changes made (diff)
Show a Specific Commit:
git show <commit-hash>
Example:
git show a1b2c3d
Displays all the details of that specific commit.
🔹 Show Only the File Names Changed:
git show --name-only <commit-hash>
🔹 Show With File Changes in a Compact Form:
git show --stat <commit-hash>
Gives a summary: number of insertions/deletions, files modified, etc.
🔹 Show Changes of a Specific File in a Commit:
git show <commit-hash>:<file-path>
Example:
git show a1b2c3d:file.txt
Shows the content of file.txt in that commit.
🔹 Preview What Was Staged (For Current Commit):
git show :file.txt
Git blame
Git blame – View Line-by-Line History in Git
The git blame command is used to display the author, revision (commit hash), and timestamp for
each line of a file. It helps you find out who changed what and when, line by line.
✅ Basic Syntax
git blame <filename>
Example:
git blame main.java
This will show output like:
a1b2c3d4 (Shyam Singh 2023-12-21 10:30:45 +0530) int total = calculateSum(arr);
📌 Output Breakdown
Each line output includes:
✅ Commit Hash – First few characters of the commit
👤 Author Name – Who made the change
🕒 Date & Time – When the change was made
📄 Line Content – The actual line of code/text
Common Options
1. Show specific lines only
git blame -L <start>,<end> <filename>
Example:
git blame -L 10,20 main.java
Shows blame info only from lines 10 to 20.
2. Ignore whitespace changes
git blame -w <filename>
Useful when lines have changed only due to indentation or formatting.
3. Show detailed commit info with --show-name
git blame --show-name <filename>
4. Blame for a specific revision
git blame <commit-hash> -- <filename>
View the state of blame as of a specific commit.
🎯 Use Case
Use git blame when:
You want to know who last edited a specific line.
You are debugging a bug and need to trace its origin.
You're reviewing changes made in a large file over time.
git status
git status – Check the Current State of Your Git Working Directory
The git status command displays the state of the working directory and staging area. It shows which
files are:
✅ Staged for commit
✏️Modified but not staged
🆕 Untracked
🔁 In conflict
✅ Basic Syntax
git status
📌 Output Explanation
When you run git status, you typically see:
🔹 On branch main
Indicates the current branch.
🔹 Your branch is up to date with 'origin/main'
Means your local branch matches the remote branch.
🔹 Changes to be committed:
Files that have been added to the staging area using git add.
🔹 Changes not staged for commit:
Files that have been modified but not yet staged.
🔹 Untracked files:
New files in the working directory not tracked by Git.
Useful Commands Related to git status
➕ Add a file to staging:
git add <filename>
➖ Remove a file from staging:
git restore --staged <filename>
🧹 Remove untracked files (be careful!):
git clean -f
♻️Discard changes in a file:
git restore <filename>
Git Staging Area (Index)
🔹 What is the Staging Area?
The Staging Area, also called the Index, is a place where Git prepares files before committing them.
It acts as a middle layer between your working directory and the repository.
You decide which changes go into the next commit by adding them to the staging area.
📌 Git Workflow Overview
Working Directory → Staging Area → Git Repository
(modify files) (git add) (git commit)
🎯 Why Use the Staging Area?
Allows selective commits (commit only what you want).
Gives you control over version history.
Helps group related changes into meaningful commits.
🧨 git reset --hard – Reset Your Repository Forcefully
🔹 What It Does
The git reset --hard command resets your working directory and staging area (index) to match a
specific commit. It discards all changes, including:
✅ Uncommitted changes in tracked files (working directory)
✅ Staged changes (staging area)
✅ HEAD pointer is moved to the target commit
⚠️Warning: This action is destructive — all discarded changes are permanently lost (unless backed
up).
✅ Basic Syntax
git reset --hard <commit-hash>
Moves HEAD to the given commit
Updates staging area and working directory
🔁 Common Usage Examples
1. Reset to the latest commit
git reset --hard HEAD
Discards all uncommitted and staged changes.
2. Reset to the previous commit
git reset --hard HEAD~1
Removes the last commit and all associated changes.
3. Reset to a specific commit
git reset --hard a1b2c3d
Resets everything to a specific commit hash.
📌 Breakdown of Effects
Area After git reset --hard
Working Directory Reset to commit state
Staging Area Cleared and reset to commit state
Commit History HEAD moved to new commit
🔒 Safety Tip
Before running git reset --hard, it's a good idea to backup with:
git stash
or create a new branch:
git checkout -b backup-branch
🎯 Use Cases
Undo changes and start fresh
Remove unwanted commits
Quickly roll back to a known good state
🔁 git revert – Safely Undo a Commit by Creating a New One
🔹 What is git revert?
The git revert command is used to undo a specific commit by creating a new commit that reverses
the changes introduced by the original one.
It is safe and non-destructive — unlike git reset, it preserves the commit history.
✅ Basic Syntax
git revert <commit-hash>
🔁 What Happens Internally?
Git creates a new commit that applies the opposite changes of the specified commit.
The original commit stays in the history.
📌 Example
git revert a1b2c3d
If commit a1b2c3d added a line, the new commit will remove that line.
⚙️Common Options
1. Revert the last commit
git revert HEAD
2. Revert multiple commits
git revert <oldest-commit>^..<latest-commit>
3. Revert without opening an editor
git revert --no-edit <commit-hash>
🧠 Difference: git revert vs git reset
Feature git revert git reset
Safe? ✅ Yes (preserves history) ❌ No (can remove history)
Creates Commit? ✅ Yes ❌ No (unless using --soft)
Collaborative? ✅ Yes (good for shared branches) ❌ Risky on shared branches
🎯 Use Cases
Safely undo a buggy commit on a shared/public branch
Maintain a clean and traceable history
Fix a mistake without rewriting commit history
itHub is a web-based platform that provides hosting for Git repositories. It allows developers to
store, manage, share, and collaborate on code.
It is built on top of Git, a version control system, and adds powerful features like issue tracking, pull
requests, actions, and project management tools.
🔑 Key Features of GitHub
Feature Description
Repository Hosting Host Git repositories (public or private)
👥 Collaboration Work with teams using branches, pull requests, and code reviews
✅ Version Control Track and manage changes using Git
🔄 Pull Requests Propose changes and review code before merging into the main branch
🐞 Issue Tracking Report and manage bugs or feature requests
⚙️GitHub Actions Automate workflows like CI/CD pipelines
🌐 Pages Host static websites directly from a GitHub repository
🔐 Security & Permissions Control access to repositories and set contributor roles
🧠 Why Use GitHub?
📁 Store your code in the cloud
🔁 Track changes over time
🧑💻 Collaborate with others
💼 Showcase projects to recruiters (portfolio)
🧪 Run automated tests and deployments
✅ Basic Workflow on GitHub
1. Create a repository
2. Clone it to your local machine
3. Make changes and commit them
4. Push changes to GitHub
5. Collaborators can pull and contribute
Popular Git Servers
A Git server is a platform that allows developers to host, manage, and collaborate on Git
repositories. These servers support version control, access control, and collaborative tools.
🏆 1. GitHub – Most Popular
🌍 Website: https://github.com
🏢 Owned by: Microsoft
📌 Features:
o Public and private repositories
o Pull requests and code reviews
o GitHub Actions (CI/CD)
o GitHub Pages for website hosting
💡 Best for: Open-source projects and personal portfolios
🏢 2. GitLab
🌍 Website: https://gitlab.com
📌 Features:
o Built-in CI/CD pipelines
o Issue tracking and project management
o Self-hosting available (GitLab CE)
💡 Best for: Enterprises and DevOps-focused teams
🧑💼 3. Bitbucket
🌍 Website: https://bitbucket.org
🏢 Owned by: Atlassian
📌 Features:
o Integration with Jira and Trello
o Supports Git and Mercurial (deprecated)
o Free private repositories
💡 Best for: Teams using Atlassian tools
git remote – Manage Remote Repositories in Git
🔹 What is a Remote?
A remote in Git is a reference to a version of your repository hosted on the internet or network. It
allows you to collaborate with others by pushing and pulling code changes.
✅ Basic Command
bash
CopyEdit
git remote
Displays the names of remotes associated with your local repository.
🧰 Common git remote Commands
Command Description
git remote Lists the remote names (e.g., origin)
git remote -v Lists remote URLs (for fetch and push)
git remote add <name> <url> Adds a new remote
git remote remove <name> Removes a remote
git remote rename <old> <new> Renames a remote
git remote set-url <name> <new-url> Changes the URL of an existing remote
📌 Example Usage
1. Add a remote
bash
CopyEdit
git remote add origin https://github.com/username/repo.git
2. View remotes
bash
CopyEdit
git remote -v
3. Remove a remote
bash
CopyEdit
git remote remove origin
4. Rename a remote
bash
CopyEdit
git remote rename origin upstream
5. Change remote URL
bash
CopyEdit
git remote set-url origin https://github.com/newuser/newrepo.git
🧠 Notes
origin is the default name Git gives to the remote you clone from.
Remotes are not copies, but pointers to repositories hosted elsewhere.
Use remotes to collaborate, sync, and deploy code.
git push – Upload Local Commits to a Remote Repository
🔹 What is git push?
git push is used to upload your local commits to a remote repository (like GitHub, GitLab, Bitbucket,
etc.).
It syncs your local branch with the corresponding remote branch.
✅ Basic Syntax
bash
CopyEdit
git push <remote-name> <branch-name>
Example:
bash
CopyEdit
git push origin main
Pushes the main branch to the remote named origin.
🧰 Common git push Commands
Command Description
git push Pushes current branch to default remote (usually origin)
Command Description
git push origin main Pushes the main branch to origin
git push -u origin main Pushes and sets upstream (link local branch with remote)
git push --force Forcefully push, overwriting remote history (⚠️Use with care)
git push origin --delete <branch> Deletes a branch on the remote repository
📌 What Happens Internally?
Git sends your commits to the remote repository.
If the remote has new commits that your local branch doesn’t, Git may reject the push (use
git pull first).
🔄 Example Workflow
bash
CopyEdit
git add .
git commit -m "Added new feature"
git push origin main
🧠 Notes
🔐 You may be asked to authenticate (e.g., with a token or SSH key).
💡 Use git push -u origin <branch> once to link the branch, then just use git push afterward.
🛑 Avoid --force unless you know exactly what you're doing.
🆚 git push vs git pull
git push git pull
Uploads local commits Downloads remote commits
Sends changes to remote Merges changes from remote
Used after committing Used before pushing or updating
SSH (Secure Shell)
🔹 What is SSH?
SSH (Secure Shell) is a network protocol that allows you to securely connect to and communicate
with a remote machine over an unsecured network.
In the context of Git and GitHub, SSH is used to authenticate and securely push/pull code without
entering your username and password every time.
🧰 SSH in Git
SSH is commonly used to connect your local Git to GitHub/GitLab/etc. without using HTTPS and
credentials repeatedly.
✅ Benefits of Using SSH with Git
🔒 Secure connection (encrypted)
🚫 No need to enter credentials every time
📂 Useful for automation (scripts, CI/CD)
📌 Common SSH Commands
Command Description
ssh-keygen -t rsa -b 4096 -C "[email protected]" Creates a new SSH key
cat ~/.ssh/id_rsa.pub Displays your public key (to copy to GitHub/GitLab)
ssh-add ~/.ssh/id_rsa Adds SSH key to your SSH agent
ssh -T [email protected] Tests your SSH connection to GitHub
SSH Keys vs GPG Keys
Both SSH keys and GPG keys are used for secure communication but serve different purposes in a
software development environment. Here's a breakdown of each:
1. SSH Keys (Secure Shell)
What is an SSH Key?
SSH keys are used for secure communication between your local machine and a remote
server (e.g., GitHub, GitLab, etc.).
Commonly used for authentication to avoid entering your username and password each
time.
Usage:
Git: For authenticating when you push or pull code from repositories.
Server Access: Secure access to remote servers without using passwords.
File Transfer: Used in tools like scp or rsync for secure file transfers.
How SSH Keys Work:
Private Key: Stored on your machine and should never be shared.
Public Key: Shared with the server (e.g., GitHub), and it's used to verify your identity.
Common Command:
bash
CopyEdit
2. GPG Keys (GNU Privacy Guard)
What is a GPG Key?
GPG (GNU Privacy Guard) is used for encryption and digital signatures. It ensures that data is
confidential and authentic.
It provides privacy (encryption) and authentication (signing), and is typically used for email
encryption and verifying the authenticity of commits or tags in Git.
Usage:
Email Encryption: Encrypt your emails to keep them private.
Git Commit Signing: Sign your Git commits and tags to ensure the authenticity of the source
code and to prove that the commits came from you.
Authentication: Used in many services to verify the identity of users.
How GPG Keys Work:
Private Key: Used for signing commits or decrypting messages. Never shared.
Public Key: Used by others to verify your signed commits or encrypted messages. Can be
shared.
Common Command:
bash
CopyEdit
gpg --full-generate-key
Key Differences Between SSH and GPG
Feature SSH Keys GPG Keys
Secure authentication with remote Encryption and signing of data (emails,
Primary Purpose
servers commits, etc.)
Common Use
Git authentication, remote server login Signing Git commits, email encryption
Case
Private key (keep secure), public key Private key (keep secure), public key
Key Pair
(share with server) (share with others)
Protocol Used SSH (Secure Shell) OpenPGP (for encryption and signing)
Command
ssh-keygen -t ed25519 -C "email" gpg --full-generate-key
Example
💬 "Someone else made changes to the code and already merged them, but I also made changes
(maybe in the same or different lines). How do I first pull their changes without losing my changes,
and then push everything correctly?"
Let me explain this step-by-step with all the necessary Git commands ✅
🔧 Scenario Setup
Let's say you're working on a file main.js.
While you were editing, someone else already merged their changes into the remote branch
(e.g., main).
You want to:
1. First get their changes.
2. Keep your changes safe.
3. Push your work (merged with theirs) later.
✅ Step-by-Step Git Commands
🔹 Step 1: Make Sure You’re on the Correct Branch
bash
CopyEdit
git status
Check you’re on the correct branch (e.g., main, develop, etc.).
🔹 Step 2: Stash Your Local Changes (Optional but Safe Way)
If you are in the middle of editing, stash them first to avoid any merge conflict.
bash
CopyEdit
git stash
✅ This saves your changes temporarily and gives you a clean state to pull from the remote.
🔹 Step 3: Pull the Latest Code from Remote
bash
CopyEdit
git pull origin main
This command pulls the latest version of the main branch from the remote.
🔹 Step 4: Apply Your Stashed Changes Back
Now bring your local changes back.
bash
CopyEdit
git stash pop
🔁 This applies your stashed code on top of the pulled (latest) code.
🔹 Step 5: Resolve Any Conflicts (if needed)
If both you and the other developer changed the same lines, you’ll get a merge conflict.
Git will mark those areas like this:
diff
CopyEdit
<<<<<<< HEAD
code from remote (merged earlier)
=======
your local changes
>>>>>>> stash
✅ Fix it manually and then do:
bash
CopyEdit
git add <filename>
git commit -m "Resolved conflict and added my changes"
🔹 Step 6: Push Your Final Code to Remote
bash
CopyEdit
git push origin main
💡 Quick Alternative (without stash):
If your local changes are not conflicting and you're confident:
bash
CopyEdit
git pull --rebase origin main
This tells Git to:
Temporarily set aside your changes
Pull and apply the new remote changes
Then replay your changes on top of it (like smart merging)
Summary Cheat Sheet for You to Save
bash
CopyEdit
# 1. Check current status
git status
# 2. Stash local changes
git stash
# 3. Pull the latest code
git pull origin main
# 4. Apply your changes back
git stash pop
# 5. Fix any conflicts, then:
git add .
git commit -m "merged latest changes and resolved conflicts"
# 6. Push to remote
git push origin main
🧠 Scenario:
1. You made local changes to a file (e.g., main.js).
2. Someone else already merged new code into the same file (maybe same or different part).
3. By mistake, you ran:
bash
CopyEdit
git pull origin main
4. Now your local file has conflicts, or your changes got mixed or overwritten.
✅ Goal:
Restore your changes as they were before the pull, and also keep the pulled changes so that you can
later merge both cleanly.
💡 Solution Plan:
🛑 Step 1: Don’t Panic. Immediately STOP working on the files.
🔄 Step 2: Check Git Status
bash
CopyEdit
git status
This will show if:
You’re in the middle of a merge conflict, or
Your changes were overwritten
✅ If You See a Merge Conflict
You can manually fix conflicts now or abort the merge and try again safely.
👉 To Abort the Pull/Merge:
bash
CopyEdit
git merge --abort
✅ This cancels the merge, and Git will restore your files to the state before the pull, so your changes
are safe.
😓 If You Already Completed the Pull (Accidentally Overwritten Your Changes)
No worries. You can use this:
bash
CopyEdit
git reflog
It will show something like:
bash
CopyEdit
a1b2c3d HEAD@{0}: pull: Fast-forward
d4e5f6g HEAD@{1}: edit main.js
...
💡 Use git checkout or git restore to recover the version before pull
bash
CopyEdit
# To restore file to the version before pull
git checkout HEAD@{1} -- main.js
or (safer for latest Git)
bash
CopyEdit
git restore --source=HEAD@{1} main.js
✅ This command restores your local file (main.js) to how it was before the pull, keeping your
changes.
🧠 Extra Safety: Stash Before Anything Risky
Even in such cases, you can always stash:
bash
CopyEdit
git stash
# Or stash even untracked files
git stash -u
📝 Summary – What To Do If You Pulled By Mistake
Situation Solution
Merge conflict after pull git merge --abort
Want to get back your changes git reflog → then git restore --source=HEAD@{1}
Didn’t commit yet? Use git stash first, then pull again safely
Want to merge later manually git stash, git pull, then git stash pop
🧠 Scenario:
You made some changes to a file.
You did:
bash
CopyEdit
git add .
git commit -m "My changes"
Now you're trying to push:
bash
CopyEdit
git push origin main
But Git says:
pgsql
CopyEdit
! [rejected] main -> main (fetch first)
error: failed to push some refs to 'origin'
hint: Updates were rejected because the remote contains work that you do
not have locally. This is usually caused by another repository pushing
to the same ref.
🎯 Your Goal:
You want to:
1. Pull the latest code (merged by others),
2. Keep your committed changes, and
3. Push everything together.
✅ Solution (Safe Steps)
🔁 Step 1: Pull with Rebase (Best Practice)
bash
CopyEdit
git pull --rebase origin main
This tells Git to:
First fetch latest code,
Then temporarily remove your commit(s),
Apply the remote changes,
Replay your commit(s) on top of latest code.
✅ This avoids a merge commit and keeps history clean.
✅ Step 2: Resolve Any Conflicts (If Needed)
If there's a conflict, Git will pause and show the file(s). You must fix them manually.
Then run:
bash
CopyEdit
git add .
git rebase --continue
Repeat if multiple conflicts.
🚀 Step 3: Now Push
bash
CopyEdit
git push origin main
Done!
❗ If You Already Did git pull and Got Merge Commit
It’s still okay.
You can just:
bash
CopyEdit
git push origin main
But your commit history will look like:
sql
CopyEdit
Merge branch 'main' of origin into main
Your commit
This is okay, just a bit messy. If you prefer clean history, always use --rebase.
📝 Summary for Your Notes
Step Command Purpose
Pull latest code and reapply your
1 git pull --rebase origin main
commits
(if conflicts) fix them, then git add . and git rebase --
2 Resolve issues
continue
3 git push origin main Push your code after clean rebase
What is a Git Branch?
A branch in Git is like a separate workspace or timeline. It allows you to:
Work on new features without affecting the main code (main or master)
Experiment or fix bugs
Collaborate with team members safely
📌 Default Branch
When you initialize a Git repo, the default branch is usually:
main
✅ Basic Branch Workflow
🔹 Step 1: Create a New Branch
git branch feature1
👉 This creates a branch named feature1 from the current branch.
🔹 Step 2: Switch to That Branch
git checkout feature1
OR shortcut (recommended):
git switch feature1
🔹 Step 3: Do Some Work (Edit files, etc.)
git add .
git commit -m "Added new feature"
You’re now committing only to feature1, not main.
🔹 Step 4: Switch Back to Main Branch
git switch main
Your main code remains unchanged.
🔹 Step 5: Merge the Feature Branch into Main
git merge feature1
Now the changes from feature1 are merged into main.
🔹 Step 6: Delete Feature Branch (Optional)
If you're done with it:
git branch -d feature1
🔄 Full Example
git init
git checkout -b login-feature
# (do changes)
git add .
git commit -m "Login page UI"
git switch main
git merge login-feature
git push origin main
🚀 Working with Remote Branches
🔹 Create and Push a New Branch
git push -u origin feature1
-u links your local branch to the remote one for easier future pushes:
git push
🔹 See All Branches
Local: git branch
Remote: git branch -r
All: git branch -a
🔹 Delete Remote Branch
git push origin --delete feature1
🧾 Summary Table
Command Description
git branch List branches
Command Description
git branch <name> Create branch
git switch <name> Switch to branch
git checkout -b <name> Create and switch
git merge <branch> Merge to current branch
git branch -d <branch> Delete local branch
git push -u origin <branch> Push new branch to remote
git push origin --delete <branch> Delete remote branch
🔐 Real-world Usage Example
Let’s say you’re working in a team:
main → production code
feature/login → user works on login
feature/signup → another dev works on signup
bugfix/navbar → quick fix by someone
All these branches are isolated, and merged back to main only after they’re reviewed/tested.
Creating a Pull Request (PR) & Merging on GitHub
🧱 What is a Pull Request (PR)?
A Pull Request is a way to propose changes from one branch (usually a feature branch) into another
branch (usually main or develop) on a remote Git server (like GitHub, GitLab, Bitbucket).
✅ Step-by-Step Process
🔹 1. Push Your Local Feature Branch to GitHub
git push -u origin feature/your-branch-name
✅ Now the branch is available on GitHub.
🔹 2. Go to GitHub Repository
Navigate to your repository on GitHub.
You'll see a message:
👉 "Compare & pull request" button next to your newly pushed branch.
🔘 Click it to create a Pull Request.
🔹 3. Create the Pull Request
Base branch = the branch you want to merge into (usually main).
Compare branch = your feature branch.
Fill in:
Title
Description of your changes
Then click:
Create Pull Request
🔹 4. Review and Merge
Review the changes.
GitHub shows all commits and files changed.
Click Merge pull request.
Confirm by clicking Confirm merge.
✅ Your code is now merged into the base branch on the server.
🎯 Visual Summary (GitHub Workflow)
Your Local Repo
|--> git checkout -b feature/login
|--> make changes + commit
|--> git push -u origin feature/login
GitHub shows "Compare & Pull Request"
Open PR → Review → Merge Pull Request
🧠 Notes
You can also assign reviewers, add labels, and link issues in a PR.
Once merged, you can delete the feature branch on GitHub.
🧹 Cleanup (Optional)
After merging:
# Delete local branch
git branch -d feature/your-branch-name
# Delete remote branch
git push origin --delete feature/your-branch-name
Git Merge vs Git Rebase
Both merge and rebase are used to combine changes from one branch into another, but they work
differently.
🧪 Scenario Example
You are on a feature branch, and the main branch has new commits.
You want to bring main into your feature branch before pushing or merging your work.
🔀 1. git merge
✅ Definition:
Combines the histories of two branches into one. Keeps all the commit history and creates a merge
commit.
🧾 Command:
bash
CopyEdit
git checkout feature
git merge main
🟢 Pros:
Keeps complete history.
Good for team collaboration.
Shows the actual merge point in history.
🔴 Cons:
Commit history can become messy with lots of merge commits.
📈 History After Merge:
css
CopyEdit
A---B---C (main)
\ \
D---E---F---M (feature)
M is a merge commit.
🔁 2. git rebase
✅ Definition:
Moves (or “rebases”) your feature branch commits on top of another branch, creating a linear
history.
🧾 Command:
bash
CopyEdit
git checkout feature
git rebase main
🟢 Pros:
Cleaner, linear commit history.
Easier to read logs and history (git log).
🔴 Cons:
Rewrites commit history → not safe for public/shared branches.
Can be confusing with conflicts.
📈 History After Rebase:
lua
CopyEdit
A---B---C (main)
\
D'---E'---F' (feature)
Commits are rebased (copied) as new ones.
🆚 Comparison Table
Feature git merge git rebase
Non-linear (with merge
History Linear (no merge commits)
commits)
Commit Integrity Keeps original commits intact Rewrites commits (new hashes)
Use in Shared Branches ✅ Yes ❌ No (unless you know what you're doing)
Complexity Simple Can be complex with conflicts
Preferred for Team collaboration Clean personal branch history
🎯 Best Practices
Use merge when working in a team.
Use rebase to tidy up your local commits before pushing.
Never rebase public branches unless everyone agrees.
✅ Common Rebase Use Case
bash
CopyEdit
# Rebase your local feature branch before creating PR
git checkout feature
git fetch origin
git rebase origin/main
Then resolve any conflicts, and finally:
bash
CopyEdit
git push --force-with-lease
Git Stash
✅ Definition:
git stash temporarily saves your uncommitted changes (both staged and unstaged) so you can work
on something else, and then come back to your changes later.
📌 Why Use git stash?
You’re working on a feature but need to switch branches quickly.
You want to pull latest changes but your work isn't ready to commit.
You're troubleshooting and want to test something without losing your current work.
🔧 Basic Command:
bash
CopyEdit
git stash
This stashes all modified and staged files.
📄 Example:
bash
CopyEdit
# You have made some changes
git status
# output shows modified files
# Save them temporarily
git stash
# Your working directory is now clean
git status
# No changes
📥 Retrieve Stashed Work
To apply the latest stash:
bash
CopyEdit
git stash apply
To apply AND remove from stash list:
bash
CopyEdit
git stash pop
📚 View All Stashes
bash
CopyEdit
git stash list
Example output:
pgsql
CopyEdit
stash@{0}: WIP on main: e13c2b2 add login feature
stash@{1}: WIP on main: 4ac8a1e update navbar
🔍 View a Specific Stash
bash
CopyEdit
git stash show stash@{0}
To see full diff:
bash
CopyEdit
git stash show -p stash@{0}
🧹 Drop a Stash (Delete)
bash
CopyEdit
git stash drop stash@{0}
🚽 Clear All Stashes
bash
CopyEdit
git stash clear
📝 Stash with a Message
bash
CopyEdit
git stash push -m "WIP: fixing navbar layout"
📂 Stash Specific Files
bash
CopyEdit
git stash push path/to/file.txt
🆚 Staged vs Unstaged?
git stash saves both staged and unstaged changes.
It does not stash untracked files unless you use:
bash
CopyEdit
git stash -u # include untracked files
git stash -a # include untracked + ignored files
💡 Real World Use Case
bash
CopyEdit
# Made some changes on branch 'main'
# But you need to checkout 'hotfix' branch
git stash # save current changes
git checkout hotfix
# work and commit on hotfix
git checkout main
git stash pop # get back to original changes