2

Git如何恢复被搁置的修改记录

 2 years ago
source link: https://www.fly63.com/article/detial/11538
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

像 git stash和 git stash pop 这样的命令是用来搁置(藏匿)和恢复我们工作目录中的变化的。在本教程中,我们将学习如何在 Git 中恢复隐藏的修改记录。

在工作目录中存储更改

在我们的例子中,假设我们已经克隆了一个 Git Repo 。现在,让我们对 README.md 文件做一些修改,只需在最后添加一行,并检查我们工作目录的状态。

$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git restore <file>..." to discard changes in working directory)
        modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")

在这里,我们可以使用 git stash 命令来暂时搁置我们的修改。

$ git stash
Saved working directory and index state WIP on master: sdfkdsx Updated pom.xml

现在,如果再做一次 git status,我们会看到我们的工作目录是干净的。

$ git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

恢复存储的变化并找到哈希值

让我们来看看如何恢复隐藏的修改,并找到与隐藏的提交相关的哈希值。

将隐藏的修改恢复到工作目录中

我们可以像这样把隐藏的修改带回到我们的工作目录中。

$ git stash pop
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git restore <file>..." to discard changes in working directory)
        modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs...

正如我们在最后一行看到的那样,git stash pop 不仅恢复了被存储的修改,而且还删除了对其相关提交的引用。

当终端打开时定位哈希值

如果我们的终端仍然是开放的,我们可以很容易地找到执行 git stash pop 后产生的哈希值。在我们的例子中,显示在最后一行的哈希值是59861637... 。

在终端关闭后恢复哈希值

即使我们已经关闭了终端,我们仍然可以通过以下方式找到我们的哈希值。

$ git fsck --no-reflog
Checking object directories: 100% (256/256), done.
Checking objects: 100% (302901/302901), done.
commit 598616...

现在我们可以看到被丢弃的储藏室的提交哈希值了。

恢复被丢弃的储藏库

通常情况下,一旦我们应用了一个储藏库条目,我们就不需要它了。然而,在某些情况下,我们可能希望在丢弃一个储藏库条目之后再去找它。例如,如果使用 git reset -hard HEAD 会丢掉我们工作目录中所有未提交的修改。在这种情况下,我们可能希望召回一些早期的藏匿修改,尽管它们被丢弃了。

使用哈希值来恢复储藏的内容

使用哈希值来处理悬空的提交,我们仍然有可能恢复这些变化。

$ git stash apply 59861637f...
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git restore <file>..." to discard changes in working directory)
        modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")

我们可以看到,我们的工作目录已经恢复了先前所隐藏的变化。

找到所有的哈希提交

如果我们没有现成的哈希值,我们可以找到它。

git fsck --no-flog | awk '/commit/ {print $3}'

这里,我们把 -no-flog 选项和 awk 结合起来,只为我们过滤出哈希值。

在这篇文章中,我们看到了git stash 是如何工作的,以及当我们使用它时它是如何丢弃一个条目的。当我们知道一个被丢弃的条目的哈希值时,我们仍然可以使用它,以及如何找到提交的哈希值.

链接: https://www.fly63.com/article/detial/11538


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK