How to Check Out a Remote Git Branch
To check out a remote Git branch, you need to fetch the branch first (if not already available locally) and then create a local branch to track it. Here’s a detailed guide with examples:
Steps to Check Out a Remote Git Branch
1. List All Remote Branches
To view all branches in the remote repository:
git fetch
git branch -r
Example Output:
origin/main
origin/feature/new-feature
origin/bugfix/123
2. Check Out the Remote Branch
You can directly check out a remote branch by creating a local branch that tracks it.
Command:
git checkout -b <local-branch-name> origin/<remote-branch-name>
Example:
To check out the remote branch feature/new-feature:
git checkout -b new-feature origin/feature/new-feature
This command:
- Creates a new local branch
new-feature. - Sets it to track the remote branch
origin/feature/new-feature. - Switches to the newly created branch.
3. Verify Tracking
To confirm that the local branch is tracking the correct remote branch:
git branch -vv
Example Output:
* new-feature 12345abc [origin/feature/new-feature] Commit message
The [origin/feature/new-feature] confirms tracking.
4. Shortcut (Using Git v2.23+)
Git introduced the git switch command as a simpler alternative.
Command:
git switch -c <local-branch-name> origin/<remote-branch-name>
Example:
git switch -c new-feature origin/feature/new-feature
5. Check Out an Existing Local Branch
If you’ve already checked out the branch earlier:
git checkout <branch-name>
Example:
git checkout new-feature
6. Fetch Updates from Remote
To ensure you have the latest changes from the remote branch:
git pull
Common Scenarios and Solutions
What If the Branch Already Exists Locally?
If you try to create a branch that already exists locally:
git checkout <branch-name>
What If the Remote Branch Isn’t Listed?
If you don’t see the branch in git branch -r:
- Fetch all branches:bash
git fetch --all - Then, try checking out
git checkout -b <local-branch-name> origin/<remote-branch-name>
What If You Want to Track an Existing Remote Branch?
If a local branch exists but isn’t tracking a remote branch:
git branch --set-upstream-to=origin/<remote-branch-name>
Example:
git branch --set-upstream-to=origin/feature/new-feature
Summary of Key Commands
| Command | Description |
|---|---|
git branch -r | Lists all remote branches. |
git checkout -b <local> origin/<remote> | Creates and checks out a local branch tracking the remote one. |
git switch -c <local> origin/<remote> | Alternative to checkout (requires Git v2.23+). |
git branch --set-upstream-to=origin/<remote> | Links an existing local branch to a remote branch. |
No images available.