This post will discuss how to create and push a branch to a remote Git repository.

The idea is straightforward here. First, you create your branch locally and push the branch to the remote repository. We can do this in two ways:

1. git-checkout

We can use the git-checkout command with the -b option to create a new branch. It creates a new branch with the specified name and then checks it out.

# Create a branch locally and check it out
git checkout -b <branch>
 
# Push the branch to the remote and set upstream
git push [-u | --set-upstream] <remote> <branch>

Here <remote> is the current branch’s remote (typically origin) and <branch> is the name of the branch. The --set-upstream (or -u) set the upstream branch for the given branch. If the --set-upstream option is skipped, git pull and some other commands will fail. You can also push a new branch upstream later with the git push -u command.

git checkout -b

2. git-branch

Another option is to use the git-branch. The following code will create a new branch named <branch>, which points to the current branch’s HEAD and then push it to the remote repository.

# Creates a local branch
git branch <branch>
 
# Push the branch to the remote and set upstream
git push [-u | --set-upstream] <remote> <branch>

That’s all about creating and pushing a branch to a remote Git repository.