Git:根据主服务器上未进行的 / 未提交的更改创建分支

上下文:我正在为 master 添加一个简单功能。几分钟后,我意识到这并不是那么简单,进入一个新分支应该更好。

这总是发生在我身上,我不知道如何切换到另一个分支,并在我离开主分支的情况下进行所有这些未提交的更改。我以为git stash && git stash branch 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")

你知道有没有办法做到这一点?

答案

git checkout -b new_branch_name
M   testing
git checkout master -f
git checkout new_branch
git commit -a -m"edited"
git checkout master
git status
git stash
git checkout -b new-branch
git stash apply
git checkout -b sillyname
git commit -am "silly message"
git checkout -
git stash -u
git branch sillyname stash@{0}

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

在此处输入图片说明

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

在此处输入图片说明

如果您只是简单地切换分支,同样适用。