我无意中把错误的文件给了Git, 但还没有把承诺推到服务器上。

我如何从当地存储库撤销这些承诺?


当前回答

#1) $ git commit -m "Something terribly misguided" 
#2) $ git reset HEAD~                              

[必要时编辑文件]

 #3) $ git add .
#4) $ git commit -c ORIG_HEAD  

其他回答

键入 git 日志, 并找到最后一次承诺的散列代码, 然后输入 :

git reset <the previous co>
git reset --soft HEAD~1

软性 : 这将只从本地端删除承诺, 并保留文件所做的更改 。

    git reset --hard HEAD~1
    git push origin master

硬性 : 这将从本地和远程删除承诺, 并删除文件中所做的更改 。

如果您想要还原最后一个任务, 但仍要保留在任务中本地作出的更改, 请使用此命令 :

git reset HEAD~1 --mixed

如果你们在本地做出你们不喜欢的事,而他们还没有被推倒,而你们却可以把事情重现为以往的善事。这好像坏事从未发生过。下面是这样的:

在您的终端中( 终端、 Git Bash 或 Windows 命令提示) , 浏览到您的 Git repo 的文件夹中。 运行 git 状态, 并确保您有干净的工作树。 每个承诺都有一个独特的散列( 看起来像 2f5451f ) 。 您需要找到最后一件好事的散列( 您想要返回到哪个地方 ) 。 这里有两个地方您可以看到要承诺的散列 : 在 GitHub 或 Bitbucket 网站或网站的承诺历史中 。 在您的终端中( 终端、 Git Bash 或 Windows 命令快递) 运行命令 git 日志 -- 在线, 一旦您知道最后一件好事的仓列( 您想要返回到哪个地方) , 请运行以下的命令( 将 2f5451f 与您的承诺重写 ) :

git reset 2f5451f
git reset --hard 2f5451f

注意 : 如果您确实重置承诺, 将会删除, 但更改将显示为未承诺, 允许您访问代码 。 这是最安全的选项, 因为也许您想要一些代码, 现在您可以做出一些好的更改和新承诺 。 通常您会想要撤销承诺, 丢弃代码, 这正是 Git 重置 -- hard 所做的 。

在回答之前,让我们补充一些背景,解释一下这个总部是什么。

首先,什么是总部?

HEAD 只是引用当前分支的当前承诺( 最新承诺) 。 在任何特定时间( 不包括 git worktree) 只能有一个 HEAD 。

HEAD的内容存放在.git/HEAD内,包含当前承诺的40字节SHA-1。


独立头部

如果您没有在最新的承诺 - 意思是,HEAD指向 历史的先前承诺, 它被称为独立的HEAD。

在命令行上, 它会看起来像这个 - SHA-1 而不是分支名称, 因为 HEAD 没有指向当前分支的端点 :


如何从独立的总部中恢复的几种选择:


git 检出

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits to go back

这将检查指向想要的承诺的新分支 。 此命令将检查退出给定的承诺 。 在此点上, 您可以创建一个分支, 从此开始工作 。

# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# Create a new branch forked to the given commit
git checkout -b <branch name>

git 重新格式

您也可以同时使用reflog。 git reflog 将显示任何更新 HEAD 的更改, 并检查想要的 reflog 条目, 将会将 HEAD 设置回至此任务 。

每次对总部领导部进行修改时,在重新格式中将有一个新的条目

git reflog
git checkout HEAD@{...}

这样你就可以回到你想要的事业了


git 重置 - 硬设置 < commit_ id>

"移动"你的总部 回到想要的承诺。

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.

注: (自Git 2. 7) 您也可以使用 Git rebase -- no- autostash 。


git 返回 <sha-1>

“ 撤消” 指定的承诺或承诺范围。 重置命令将“ 撤消” 对给定承诺所做的任何更改 。 在原始承诺也将保留在历史中时, 将使用撤消补丁的新承诺 。

# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>

此图示显示哪个命令做什么。 正如您可以看到的, 重置 {} 检查退出 修改 HEAD 。