If the new branch already exists in your remote repository and you already checked into the new branch, simply use git push command. However if the new branch does not exist yet in the remote repository or you are not checked into the new branch, first checkout to the new branch using git checkout <branch_name> command and then push and create the new branch in remote repository using git push -u <remote_name> <branch_name>
Example:
Create a new local git repository:
1 2 |
## Create a new local git repository git init myrepo && cd myrepo |
Create your 1st git commit:
1 2 3 4 |
## add a new file and commit echo "hello world" > file1 git add file1 git commit -m "commit1" |
Create a new remote git repository and add it to your local git repository:
1 2 3 4 5 6 7 |
## Create an empty remote git repository (i m using GitHub for this demo) ## Add your username and email to git config (optional) git config --add --local user.name cloudaffaire git config --add --local user.email cloudaffaire@gmail.com ## Add remote repository to your local repository git remote add origin git@github.com:CloudAffaire/myrepo.git git branch -M main ## rename of default local branch (master -> main) |
Now push your local default branch to the remote repository:
1 2 |
## push local repository default branch to remote repository git push -u origin main |
Next, create a new local branch:
1 2 |
## create a new local branch named feature git checkout -b feature |
Add some change and commit to the feature branch:
1 2 3 4 |
## Add some change and commit to feature branch echo "welcome to cloudaffaire" >> file1 git add file1 git commit -m "commit2" |
Finally, push your branch from local repository to remote repository:
1 2 |
## push and create the barnch in remote repository git push -u origin feature |
Next time onwards you do not need to specify the remote name or branch name to push.
Add another change and push to the remote repository:
1 2 3 4 5 |
## Add another change and push to remote repository echo "hope you have enjoyed" >> file1 git add file1 git commit -m "commit3" git push ## yeah only push this time :) |