Git Get One File From Another Repo

Git Get One File From Another Repo

Welcome to Issue #6 of Git Weekly! This week we're going to talk file and moving them around. Let's assume you have a file in one branch and you want to bring it to another one. That's tricky enough. Even trickier is this: You and your friend have forked the same repo and pushed different changes to each one. Now you want to have the changes your friend made to their fork, in your fork.

In this article, we will answer both questions:

  • Get a file from another branch on the same repo
  • Get a file from another repo

Get One File From Another Branch

Assume you want to bring a file from the branch?feature-source?into the branch?feature-dest. The file is called?package.json.

First, you need to switch to the branch?feature-dest:

git switch feature-dest        

And then bring the file from the other branch:

git checkout feature-source -- package.json        

Get One File From Another Repo

Now assume that I have forked the repo?rxjsx/rxjsx?into?aerabi/rxjsx. Then I cloned my fork to work on it locally. My amigo also forked the original repo into?amigo/rxjsx?and made a few changes and pushed them into his master branch.


Now I want to get one file from his master branch into my local repo. This is how it's done:

First copy the URL of the remote repo you want to get the file from, in this case, the?amigo/rxjsx.

Then fetch it:

git fetch [email protected]:amigo/rxjsx.git        

Git will show a message like this:

From github.com:amigo/rxjsx  * branch            HEAD       -> FETCH_HEAD
        

It means the remote repo is fetched and its?HEAD?is now named?FETCH_HEAD. Next, get the file (or directory) you want from the?FETCH_HEAD:

git checkout FETCH_HEAD -- package.json        

It's similar to the former case, the only difference is the git label you are checking out from.

Final Words

要查看或添加评论,请登录