Git branch is like a copy of your project where you can make changes without affecting the main project.

Imagine:

Working on a new feature or idea -->

We can create a branch -->

Do all your work there -->

Then decide later if you want to merge it back into the main project.

Untitled

(Source:https://www.nobledesktop.com/)

Branches allow you to work on different parts of a project without impacting the main branch.

When the work is complete, a branch can be merged with the main project.

You can even switch between branches and work on different projects without them interfering with each other.

See Your Current Branch

git status
Screenshot 2024-08-10 at 2.41.32 AM.png

Create a New Branch

git checkout -b branch-name
Screenshot 2024-08-10 at 2.39.06 AM.png

You're now ready to commit to this branch.

Switch to a Branch In Your Local Repo

git checkout branch-name
Screenshot 2024-08-10 at 2.41.12 AM.png

List All Branches

To see local branches:

git branch
Screenshot 2024-08-10 at 2.42.00 AM.png

Current local branch will be marked with an asterisk (*)

To see remote branches:

git branch -r

To see all local and remote branches:

git branch -a

Push to a Branch

If your local branch does not exist on the remote, run either of these commands:

git push -u origin branch-name
Screenshot 2024-08-10 at 2.50.38 AM.png

Merge Branch

Merging a branch means taking the changes you made in one branch and combining them with another branch, usually the main branch.

git checkout main
git merge branch-name
  1. git checkout main: Switch to the branch you want to merge into, usually the main branch.
  2. git merge branch-name: Merge the changes from my-branch-name into the main branch.
Screenshot 2024-08-10 at 2.58.24 AM.png

Delete Branch

Deleting a branch removes it from your local or remote repository once you’re done working on it.

Deletes branch locally:

git branch -d branch-name

Deletes branch from the remote repository:

git push origin --delete branch-name
Screenshot 2024-08-10 at 2.59.04 AM.png

Switch to a Branch That Came From a Remote Repo

  1. To get a list of all branches from the remote, run this command:
    • git pull
  2. Run this command to switch to the branch:
    • git checkout --track origin/my-branch-name