StackTips

Create and Manage Git Branches from Command Line

stacktips avtar

Written by

Editorial,  5 min read,  3.2K views, updated on Sept. 17, 2023

Whenever you want to commit a bug or a new feature, you need to create a branch for it, which will be a copy of your master branch. Once your fixes are ready to merge, you typically create a pull request on your new branch. The reason for this is to keep your master branch clean all the time.

1. Create a New Git Branch

Here is a list of some useful commands to help you create and manage a new branch. Please note, that before creating a new branch, pull the changes from upstream. Your master needs to be up to date.

Create the branch on your local machine and switch to this branch:

$ git checkout -b <new branch name>

Change working branch:

$ git checkout <new branch name>

Push the branch to remote git:

$ git push origin <new branch name>

When you want to commit something in your branch, be sure to be in your branch. Add -u parameter to set-upstream.

2. View Git Branches

You can see all the local branches by using:

$ git branch

View list of all branches, including remote branches:

$ git branch -a

View list of only remote branches:

$ git branch -r

3. Push Branch to Remote

Add a new remote for your branch:

$ git remote add <remote branch name>

Push changes from your commit into your branch:

$ git push <new branch remote name>  <new branch name>

Update your branch when the original branch from the official repository has been updated:

$ git fetch <remote branch name>

Then you need to apply to merge changes if your branch is derivated from the develop you need to do:

$ git merge <name of remote branch>/develop

4. Delete Git Branch

Delete local branch: -d option stands for –delete

$ git branch -d <branch_name>

Git local branch force: -D option stands for –delete –force

$ git branch -D <branch_name>

Delete a remote Git branch

$ git push origin --delete <branch_name>
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!