通过 Git 将未提交的更改放到 Master 的新分支上

当我在分支 master时,如何将未提交的更改放到分支测试中?

46301 次浏览
git checkout TEST
git add file1 file2
git commit

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

假设你在主分支:

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

我真的不知道关于删除的文件,但我猜想他们不包括当你使用 git add .

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

git checkout -b new_branch
git add .

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

为什么不直接使用 Git 存储呢? 我认为它更直观,像复制粘贴一样。

$ 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 一样,这种情况经常发生在我身上,因为我在解决一个新问题的时候忘记了我还在另一个分支上。因此,你可以 藏起来了你的工作,git flow feature finish...,和 git stash apply到新的 git flow feature start ...分支。