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
不会触及您的本地更改。 它只是从当前的HEAD创建分支并将HEAD设置在那里。 所以我想这就是你想要的。
---编辑说明结帐大师的结果---
您是否感到困惑,因为checkout master
不会放弃您的更改?
由于更改只是本地的,所以git不希望你太容易丢失它们。 更改分支后,git不会覆盖您的本地更改。 您的checkout master
的结果是:
M testing
,这意味着你的工作文件不干净。 git确实改变了HEAD,但没有覆盖你的本地文件。 这就是为什么你的最后一个地位仍然显示你的本地变化,尽管你是master
。
如果您真的想放弃本地更改,则必须使用-f
强制结帐。
git checkout master -f
由于您的更改从未提交过,您会失去它们。
尝试回到你的分支,提交你的改变,然后再次检查主人。
git checkout new_branch
git commit -a -m"edited"
git checkout master
git status
在第一次结帐后,您应该收到一条M
消息,但在checkout master
之后再也没有消息了,并且git status
应该不会显示已修改的文件。
---编辑清除工作目录(本地文件)的困惑---
在回答你的第一条评论时,当地的变化只是......好的。 Git不会自动保存它们,您必须告诉它以保存它们以备后用。 如果你进行了更改并且没有明确提交或存储它们,那么git不会对它们进行版本化。 如果您更改HEAD( checkout master
),则本地更改未被覆盖,因为未保存。
尝试:
git stash
git checkout -b new-branch
git stash apply
你可以做两件事:
git stash -u
git branch sillyname stash@{0}
要么
git checkout -b sillyname
git commit -am "silly message"
git checkout -
( git stash -u
< - -u
表示它也需要未分类的更改)
( git checkout -
< - 短划线是前一个分支的捷径)
上一篇: Git: Create a branch from unstaged/uncommitted changes on master