This article will discuss how we can push and track a new Git branch to a remote repository. Developers often have to create new branches while working on projects and publish them in the remote repository for other developers to access the changes.
But before we get into the nitty-gritty, let’s check some useful commands while working with Git branches.
Commands to Work with Branches in Git
Here are some handy commands you should have at the tip of your fingers while using Git.
We run the command below to view the branches in our Git repository.
For both our local and remote repository, we run this command.
git branch -a
If you are only interested in the remote repository, run this command.
git branch -r
$ git branch -a * main remotes/origin/HEAD -> origin/main remotes/origin/main
The asterisk (
*) points to the branch we are currently working on.
Create a New Branch in Git
We use the
git branch command while mentioning the name of the branch we desire.
git branch <branch-name>
Git will carry forward the commits of the parent branch to the new branch. Parent branch refers to the branch we are working on while creating the new branch.
The command above will only create the specified branch. To switch to the new branch, use the
git checkout command in the context shown below.
git checkout <branch-name>
To make it easier, run the command below.
git checkout -b <branch-name>
This command will create and switch to the mentioned
Rename a Branch
To rename a branch in Git, we run the command below.
git branch -m <old-branch-name> <new-branch-name>
Push a Local Branch to a Remote Repository in Git
We run the
git push command while mentioning the name of the branch. See the command below.
git push -u origin <branch-name>
Git will push the branch and set up tracking. The
-u is a short form for