Git Branching

Check all locally available branches

$ git branch

Make a new branch & Switch to new branch

$ git branch <name of the branch>   # e.g. git branch dev1
$ git checkout <name of the branch> # e.g. git checkout dev1

You can do the above 2 steps in a single line

$ git checkout -b <name of the branch> # e.g. git checkout -b dev1

Delete a branch

$ git branch -d <name of the branch> # e.g. git branch -d dev1

Delete a branch locally and remotely

Locally

Two options to delete a local branch

Option 1:

$ git checkout main   # first switch to main branch from the branch you want to delete
$ git branch -d <name of the branch to delete>

Option 2:

If you get run into an error such as the following

error: The branch 'feature' is not fully merged. If you are sure you want to delete it, run 'git branch -D feature'.

then do

$ git checkout main
$ git branch -D <name of the branch to delete>

Please note, the above command will discard all the unmerged changes

Remotely

To delete remote branch

$ git push origin -d <name of the branch to delete>

Merging two branches:

$ git checkout main              # first switch to the main/master (production) branch
$ git merge <name of the branch> # e.g. git merge dev1

View local and remote branches

To view all local and remote branches

$ git branch -a

To view only remote branches

$ git branch -r

Pull remote branches to local repo

Let's say we have "dev2" branch on our remote repo, but not locally. We can pull this branch locally and start working on it

$ git checkout dev2 # this will create a new branch called dev2 locally, which is in sync with the remote branch with the same name
$ git pull          # this will make sure that all the code from that remote branch is now pulled locally 

Set up default branch as main/master

$ git push --set-upstream origin main # sets up default remote branch as main

Last updated