
Github Branch in Git
GitHub Branch in Git – Detailed Explanation
A branch in Git is a parallel version of a repository. It allows developers to work on new features, fixes, or experiments without affecting the main codebase. GitHub branches enable collaboration by letting multiple people work on different parts of a project simultaneously.
📌 Working with Branches in Git
1️⃣ Viewing Branches
- To see all local branches:
git branch
- To see remote branches:
git branch -r
- To see both local and remote branches:
git branch -a
2️⃣ Creating a New Branch
- To create a branch but stay on the current one:
git branch feature-branch
- To create and switch to the new branch immediately:
(Newer alternative command:git checkout -b feature-branch
git switch -c feature-branch
)
3️⃣ Switching Between Branches
- Move to another branch:
(Newer alternative:git checkout feature-branch
git switch feature-branch
)
4️⃣ Pushing a New Branch to GitHub
- After creating a local branch, push it to GitHub:
Thegit push -u origin feature-branch
-u
flag sets up tracking between your local and remote branches.
5️⃣ Merging Branches
- Switch to the main branch:
git checkout main
- Ensure it's updated:
git pull origin main
- Merge the feature branch:
git merge feature-branch
- Push the updated
main
branch:git push origin main
6️⃣ Deleting a Branch
- Remove a branch locally:
git branch -d feature-branch
- Remove a branch from GitHub:
git push origin --delete feature-branch
7️⃣ Fetching and Checking Out a Remote Branch
- If the branch exists on GitHub but not locally:
git fetch origingit checkout -b feature-branch origin/feature-branch
8️⃣ Rebasing Instead of Merging
- If you want a linear history:
git checkout feature-branchgit rebase main
This moves the branch commits on top of the latest main
commits.