简体   繁体   中英

How to checkout files from another branch and then overwrite the current branch

Based on http://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/ , we can use the following command to merge changes from another branch to local branch.

For example:

$git checkout master -- hello.c

This command will merge the hello.c from master branch to current local branch.

Question> What if I want to use the hello.c from master to overwrite my local branch file without any merge? which option I should use?

Thank you

-- Update --

$ pwd
/sandbox/projectOne

$ git branch
  feature/F_Source
* feature/F_Dest
  master
$ git status -s
$
$ git diff feature/F_Source feature/F_Dest -- Messages/src/Hello.C | wc -l
165
$ git checkout feature/F_Source -- Messages/src/Hello.C
$
$ git diff feature/F_Source feature/F_Dest -- Messages/src/Hello.C | wc -l
165
$ git status -s
M  Messages/src/Hello.C
$

As you can see, before the checkout, there is a difference between F_Source Hello.C and F_Dest Hello.C. After the checkout, there is still a difference. So I assume the checkout is NOT a overwrite operation otherwise we should not see any difference.

Note this quote from the link you posted:

The code you need to grab is isolated to a handful of files, and those files don't yet exist in the master branch .

So what he is calling a "merge" is not really a merge at all; it is simply copying the files over, no merging required. When you call git checkout master -- hello.c , it is indeed overwriting your local copy of hello.c with whatever is in master ; it is not merging anything.

Question> What if I want to use the hello.c from master to overwrite my local branch file without any merge?

which option I should use?

As you already found out this is the way to do it (what you did so far)

git checkout <branch_name> -- <file path>


# On branch master - checkout different branch
git checkout <branch2>

# now checkout the desired file form different branch (master in this case)
git checkout master -- hello.c

Since you are checking out file from different branch there will be a merge. If you want not to merge simply grab the content of the file you need and overwrite it over the current file so the content will be new and it will be a simple change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM