是否可以在Git中仅提取一个文件?

问题描述 投票:155回答:5

我正在一个有一些坏测试的Git分支上工作,我想从已经固定它们的另一个分支中提取(合并更改,而不仅仅是覆盖)这些测试。

我知道我能做到

git pull origin that_other_branch

但是这将尝试合并许多其他文件,因为我尚未准备好。

是否有可能仅从另一个分支中提取并合并指定的文件(而不是所有文件)?

这不是Git pull request for just one file的重复项,因为对该问题的所有答案都是如何在不更改任何分支的情况下将本地更改的文件还原到存储库版本。

git git-merge git-pull git-fetch
5个回答
133
投票

您可以通过这种方式获取然后仅检出一个文件:

git fetch
git checkout -m <revision> <yourfilepath>
git add <yourfilepath>
git commit

关于git checkout命令:<revision>-分支名称,即origin/master<yourfilepath>不包含存储库名称(您可以通过单击GitHub上文件页面上的copy path按钮获得存储库名称),即README.md


234
投票

这是我研究此方法时想出的一种稍微容易一些的方法:

git fetch {remote}
git checkout FETCH_HEAD -- {file}

14
投票
git checkout master -- myplugin.js

master =分支名称

myplugin.js =文件名


7
投票

@ Mawardy的回答对我有用,但是我的更改在远程进行,因此我必须指定来源

git checkout origin/master -- {filename}

2
投票

是,这是过程:

# Navigate to a directory and initiate a local repository
git init        

# Add remote repository to be tracked for changes:   
git remote add origin https://github.com/username/repository_name.git

# Track all changes made on above remote repository
# This will show files on remote repository not available on local repository
git fetch

# Add file present in staging area for checkout
git check origin/master -m /path/to/file
# NOTE: /path/to/file is a relative path from repository_name
git add /path/to/file

# Verify track of file(s) being committed to local repository
git status

# Commit to local repository
git commit -m "commit message"

# You may perform a final check of the staging area again with git status
© www.soinside.com 2019 - 2024. All rights reserved.