Skip to content

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

While working on a project, it is often necessary to create different branches and push them to the remote repository. Here, you will figure out how to manage that.

Useful Commands to Work with Git Branches

Below, we will consider several handy commands that are commonly used while working with branches.

Listing branches

For viewing the branches of your git repository, you need to run the following command:

create new branches git

makefile
git branch

To view both remote and local branches, run:

view remote and local branches git

makefile
git branch -a

INFO

For listing only the remote branches, you should use the -r option instead of -a.

You will notice an asterisk (*) near the branch you are currently working on.

Creating a New Branch

For creating a new branch, you can use the git branch command by mentioning the name of the new branch:

create a new git branch

makefile
git branch <new-branch-name>

The new branch will include the commits of the parent branch. The parent branch is the one you are on while generating a new branch.

It is essential to note that the above-given command will only create a branch. For switching to it you need to run the git checkout command:

switch to the new branch git

makefile
git checkout <new-branch-name>

Instead of using the two commands above, you can just run the git checkout command with the -b option to create a new branch and checkout to it:

create a new branch and switch to the new git

makefile
git checkout -b <new-branch-name>

Renaming a Branch

For renaming a git branch, you need to run the following command:

rename git branch

makefile
git branch -m <old-branch-name> <new-branch-name>

Pushing local branch to the remote

To push the local branch to the remote repository, you should run the git push command by specifying the branch name (suppose, the name of remote is origin, which is by default):

push the local branch to the remote repository git

makefile
git push -u origin <new-branch-name>

The tracking will be set up by Git during the pushing.

The git checkout Command

As it was already mentioned, the git checkout command allows switching between branches. It works with git branch. Git checkout updates the files in the working directory to agree with the version that is in that branch, alerting Git to record all the new commits. Git checkout is also associated with the git clone command. The latter is aimed at fetching code from the remote repository. On the contrary, git checkout is switching code versions on the local repository.

Dual-run preview — compare with live Symfony routes.