上下文:我正在master上添加一个简单的功能。几分钟后,我意识到事情并没有那么简单,应该在一个新的分支工作。

这总是发生在我身上,我不知道如何切换到另一个分支,并采取所有这些未承诺的变化与我离开主分支干净。我认为git stash && git stash分支new_branch将简单地完成,但这是我得到的:

~/test $ git status
# On branch master
nothing to commit (working directory clean)

~/test $ echo "hello!" > testing 

~/test $ git status
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   testing
#
no changes added to commit (use "git add" and/or "git commit -a")

~/test $ git stash
Saved working directory and index state WIP on master: 4402b8c testing
HEAD is now at 4402b8c testing

~/test $ git status
# On branch master
nothing to commit (working directory clean)

~/test $ git stash branch new_branch
Switched to a new branch 'new_branch'
# On branch new_branch
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   testing
#
no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (db1b9a3391a82d86c9fdd26dab095ba9b820e35b)

~/test $ git s
# On branch new_branch
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   testing
#
no changes added to commit (use "git add" and/or "git commit -a")

~/test $ git checkout master
M   testing
Switched to branch 'master'

~/test $ git status
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   testing
#
no changes added to commit (use "git add" and/or "git commit -a")

你知道有什么办法可以做到吗?


当前回答

Try:

git stash
git checkout -b new-branch
git stash apply

其他回答

如果希望将当前分支上当前未提交的更改移动到新分支,请使用以下命令创建新分支并自动复制未提交的更改。

git checkout -b branch_name

这将从当前分支创建一个新分支(假设它是master),复制未提交的更改并切换到新分支。

添加文件,将更改提交给新分支。

git add .
git commit -m "First commit"

由于创建了一个新分支,在将其推到远程之前,您需要设置上游。使用下面的命令设置上游并将其推到远程。

git push --set-upstream origin feature/feature/NEWBRANCH

一旦您点击这个命令,一个新的分支将在远程创建,新的本地分支将被推送到远程。

现在,如果你想从主分支中扔掉你未提交的变更,使用:

git checkout master -f

这将在签出时丢弃任何未提交的本地更改。

Try:

git stash
git checkout -b new-branch
git stash apply

如果你正在使用GitHub Windows客户端(就像我一样),并且你正在进行未提交的更改,你希望移动到一个新的分支,你可以通过GitHub客户端简单地“创建一个新分支”。它将切换到新创建的分支并保存您的更改。

你可以做两件事:

git checkout -b sillyname
git commit -am "silly message"
git checkout - 

or

git stash -u
git branch sillyname stash@{0}

(git checkout - <——破折号是你所在的上一个分支的快捷方式)

(git stash -u <——-u表示它也接受未分阶段的更改)

在最新的GitHub Windows客户端中,如果您有未提交的更改,并选择创建一个新的分支。 它会提示你如何处理这种情况:

如果您只是简单地切换分支,也可以使用相同的方法。