【问题标题】:Putting uncommitted changes at Master to a new branch by Git通过 Git 将 Master 中未提交的更改放入新分支
【发布时间】:2010-11-24 00:10:00
【问题描述】:

当我在分支 master 时,如何将未提交的更改放入分支 TEST?

【问题讨论】:

标签: git branch master


【解决方案1】:

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

git checkout -b new_branch
git add .

我一直使用它,因为我总是忘记在开始编辑代码之前启动一个新分支。

【讨论】:

  • 与@jouni 为另一个答案指出的问题相同 - 如果其他更改与原始更改冲突,您可能会遇到将分支合并回 master 的困难。 IMO 这个帖子更好地回答了这个问题:stackoverflow.com/questions/556923/…
  • 简短、甜美、令人安心……“我一直都在用这个……”
  • 不要忘记在 new_branch 中提交。如果您切换回 master 分支并恢复更改的文件,您也会在 new_branch 中丢失它们。
【解决方案2】:

您可以只签出到测试分支然后提交。移动到另一个分支时,您不会丢失未提交的更改。

假设你在 master 分支:

git checkout test
git add .
git add deletedFile1
git add deletedFile2
...
git commit -m "My Custom Message"

我不太确定删除的文件,但我猜当您使用git add .时它们不包括在内

【讨论】:

  • 有时结帐会失败,因为您的更改与该分支冲突。你可以试试 checkout -m 来合并。
  • 我试过这个,但我得到一个错误:错误:您对以下文件的本地更改将被结帐覆盖。请在切换分支之前提交您的更改或存储它们。
  • 虽然这会起作用,但 IMO 应该首选使用 stash 的答案。也许只是个人选择,但从逻辑上讲,它是一个更干净的工作流程,并且引入了 STASH,这是一个有用的命令。
  • 缺少选项“-b”,因为标题表明问题与“新”分支有关。
【解决方案3】:

为什么不直接使用 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 ...分支。

【讨论】:

  • git stash 是我处理未提交更改的首选方式。当您将其视为剪切和粘贴时,这无疑是一种直观的方法。
  • 这对我来说似乎是个好方法。它没有问题。
  • 不知道你能做到这一点,而且效果很好。感觉比其他方法更直观。
  • 我认为 stash 是更专业的方式,而不是使用 git checkout 然后添加。我认为你的答案应该是 100+ 票。
  • @Καrτhικ git stash --include-untracked
【解决方案4】:
git checkout TEST
git add file1 file2
git commit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 2022-08-24
    • 2016-12-20
    • 1970-01-01
    • 2015-12-28
    • 2021-05-01
    • 1970-01-01
    相关资源
    最近更新 更多