How do I copy a version of a single file from one git branch to another?

你离开我真会死。 提交于 2019-11-26 16:45:53
madlep

Run this from the branch where you want the file to end up:

git checkout otherbranch myfile.txt

General formulas:

git checkout <commit_hash> <relative_path_to_file_or_dir>
git checkout <remote_name>/<branch_name> <file_or_dir>

Some notes (from comments):

  • Using the commit hash you can pull files from any commit
  • This works for files and directories
  • overwrites the file myfile.txt and mydir
  • Wildcards don't work, but relative paths do
  • Multiple paths can be specified

an alternative:

git show commit_id:path/to/file > path/to/file

I ended up at this question on a similar search. In my case I was looking to extract a file from another branch into current working directory that was different from the file's original location. Answer:

git show TREEISH:path/to/file >path/to/local/file

What about using checkout command :

  git diff --stat "$branch"
  git checkout --merge "$branch" "$file"
  git diff --stat "$branch"

Following madlep's answer you can also just copy one directory from another branch with the directory blob.

git checkout other-branch app/**

As to the op's question if you've only changed one file in there this will work fine ^_^

1) Ensure you're in branch where you need a copy of the file. for eg: i want sub branch file in master so you need to checkout or should be in master git checkout master

2) Now checkout specific file alone you want from sub branch into master,

git checkout sub_branch file_path/my_file.ext

here sub_branch means where you have that file followed by filename you need to copy.

Please note that in the accepted answer, the first option stages the entire file from the other branch (like git add ... had been performed), and that the second option just results in copying the file, but doesn't stage the changes (as if you had just edited the file manually and had outstanding differences).

Git copy file from another branch without staging it

Changes staged (e.g. git add filename):

$ git checkout directory/somefile.php feature-B

$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   directory/somefile.php

Changes outstanding (not staged or committed):

$ git show feature-B:directory/somefile.php > directory/somefile.php

$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   directory/somefile.php

no changes added to commit (use "git add" and/or "git commit -a")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!