You can use git checkout -b <local_branch_name> <remote_name>/<remote_branch_name> command to checkout to a remote git branch.
Example:
Create a new git local repository:
1 2 3 |
## Create a new git local repository cd git init myrepo1 && cd myrepo1 |
Create your 1st commit in local repository default branch:
1 2 3 4 |
## Create first commit in default branch echo "cat" > file1 git add file1 git commit -m "commit1" |
Create and add an empty remote repository to your local repository:
1 2 3 4 5 6 7 8 9 |
## Add a remote repository ## 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) git push -u origin main |
Create a new feature branch in your local repository and push it to your remote repository:
1 2 3 4 5 6 7 8 9 10 11 |
## Create a feature branch git checkout -b feature ## Create first commit in feature branch echo "cat" > file2 git add file2 git commit -m "commit2" ## Push the feature branch to remote repository git push -u origin feature ## we will use this feature branch to checkout |
This remote feature brach will be used next to demonstrate how to checkout to a remote branch in git. Next, clone the remote repository in some other place and try to switch to the remote feature branch.
Clone the remote repository and create a new local repository from it:
1 2 3 4 |
## Now clone the remote repository to some other place. cd git clone git@github.com:CloudAffaire/myrepo.git myrepo2 cd myrepo2 |
Check all git branches in the new local repository:
1 2 3 4 5 6 7 |
## Check all branched git branch -a ## returns ## * main ## remotes/origin/HEAD -> origin/main ## remotes/origin/feature ## remotes/origin/main |
Observe: git clone command also copies all remote repository branches. The same goes for git fetch and git pull.
Checkout to a remote repository branch:
1 2 3 |
## Checkout to a remote branch ## git checkout -b git checkout -b feature origin/feature |
Create the second commit in the feature branch and push the changes:
1 2 3 4 5 |
## Create second commit in feature branch echo "cow" > file3 git add file3 git commit -m "commit3" git push |
Delete both the local repository and remote repository.
1 2 |
## delete your git repository cd && rm -rf myrepo* |