将Git中Master分支的未提交更改放到一个新分支上

189

当我在分支 master 上时,如何将未提交的更改推送到分支 TEST?


2
参见: https://dev59.com/jnA85IYBdhLWcg3wF_i0 - Jouni K. Seppänen
4个回答

195

你也可以通过以下方式创建一个新的分支并切换到它:

git checkout -b new_branch
git add .

我经常使用这个功能,因为我总是忘记在开始编辑代码之前创建一个新的分支。


3
和 @jouni 在另一个答案中提到的问题相同 - 如果附加更改与原始更改冲突,将在将分支合并回主分支时遇到困难。在我看来,这个帖子更好地回答了这个问题:https://dev59.com/rXRB5IYBdhLWcg3wroyB - jpw
简短、甜美且令人放心的话:“我一直都在使用这个…” - ϹοδεMεδιϲ
1
不要忘记在new_branch中进行提交。如果您切换回主分支并还原更改的文件,则也会在new_branch中丢失它们。 - petrsyn

151
你可以直接切换到测试分支然后提交更改。当移动到另一个分支时,你不会失去未提交的更改。
假设你当前在主分支上:
git checkout test
git add .
git add deletedFile1
git add deletedFile2
...
git commit -m "My Custom Message"

我不太确定删除的文件是否包含在使用 git add . 命令时,但我猜测它们并不会被包含进去。


12
有时检出失败是因为你的更改与该分支冲突。你可以尝试使用 checkout -m 进行合并。 - Jouni K. Seppänen
2
我尝试了这个,但是出现了一个错误: 错误:您对以下文件的本地更改将被检出覆盖。在切换分支之前,请提交更改或将其存储。 - ishwr
虽然这样做是可行的,但我认为应该优先考虑使用stash的答案。也许只是个人选择,但它具有更清晰的工作流程和逻辑,并引入了STASH这个有用的命令。 - Patrick
选项“-b”丢失,正如标题所示,问题涉及“新”分支。 - Guntram

36

为什么不直接使用git stash呢?我认为它更像复制和粘贴,更加直观。

$ git branch
  develop
* master
  feature1
  TEST
$

你当前分支中有一些文件需要移动。

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#      modified:   awesome.py
#
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#
#      modified:   linez.py
#
$
$ git stash
Saved working directory and index state \
  "WIP on master: 934beef added the index file"
HEAD is now at 934beef added the index file
(To restore them type "git stash apply")
$
$ git status
# On branch master
nothing to commit (working directory clean)
$
$
$ git stash list
stash@{0}: WIP on master: 934beef ...great changes
$

移动到另一个分支。

$ git checkout TEST

并应用

$ git stash apply
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#
#      modified:   awesome.py
#      modified:   linez.py
#

我也喜欢 git stash,因为我使用 git flow,当你想要结束一个特性分支时,如果在你的工作目录中仍有更改,它会发出警告。

就像 @Mike Bethany 一样,我经常遇到这种情况,因为我在解决新问题时忘记了自己仍在其他分支上。所以你可以将你的工作 stash 起来,执行 git flow feature finish...,然后使用 git stash apply 到新的 git flow feature start ... 分支。


2
git stash 是我处理未提交更改的首选方式。当你将其视为剪切和粘贴时,它肯定是一种直观的方法。 - Matthew Mitchell
我认为使用git stash更加专业,而不是使用git checkout然后再添加。我认为你的回答应该得到100多个赞同票。 - Matrosov Oleksandr
如果您有一个新的未提交文件,git stash 将无法工作。 - Καrτhικ
1
@Καrτhικ git stash --include-untracked @Καrτhικ git stash --include-untracked - 2Toad
Stash 应用在哪个分支?测试还是主分支?看起来已经切换到测试分支,但显示为主分支? - Mayuresh Srivastava
显示剩余2条评论

5
git checkout TEST
git add file1 file2
git commit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接