How to Push and Track a New Local Git Branch to a Remote Repository

John Wachira Feb 02, 2024
How to Push and Track a New Local Git Branch to a Remote Repository

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.

List Branches

We run the command below to view the branches in our Git repository.

git branch

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

Example:

$ 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 branch-name.

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 --set-upstream.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Push