Search code examples
gitgithubbranch

Checking out a remote branch into a new branch


Goal: git checkout -b newBranchName remotes/branchForRemote/main to actually go into newBranchName

I started with an empty Git repository, which I cloned from github.com.

Then, git remote add [urlFromAnOpenSourceProject]

Then, git checkout -b newBranchName remotes/openSourceRepo/main.

The command above only pulled the remotes/openSourceRepo/main into my own main branch. How do I instead make it pull into another of my branches (not my main branch)?

Note: I have a workaround listed below, but I would still like to know how to avoid needing to use this workaround.

My workaround: Create/switch to a different branch, and then run the following commands

brew install git-lfs (if you need git-lfs for your open source project)
git clone [My repository URL]
git remote add opensource [Open source URL]
git fetch opensource
git lfs install (if the open source project uses it.)
git checkout -b branchToPullinto
git checkout -b nameThatWillNotBeUsed remotes/opensource/main
git commit -m “I pulled from opensource into the branchToPullinto branch”
git push -> Will throw an error
git push --set-upstream origin anotherNewBranch
The Command Prompt/Terminal will say:
Branch 'anotherNewBranch' set up to track remote branch 'anotherNewBranch' from 'origin'.
Now, run “git push”

Solution

  • What you're doing is about right. You just forgot a git fetch --all or git fetch <open source remote name you gave it in remote add>.

    So basically:

    1. git clone https://github.com/<url to your empty repo>
    2. git remote add opensource <link to open source project>
    3. git fetch opensource
    4. git checkout -b <any name you want> opensource/master

    Without git fetch, your Git installation doesn't know which files/branches/tags your open source remote has in the first place.