首页 > 解决方案 > GitHub如何在保留当前未提交代码的同时检查先前提交的文件?

问题描述

我知道这是一个简单的问题,但我不知道如何在 git 中做到这一点。

例如,与上次提交相比,我更改了第 10~15 行。但现在我想看看原来的第 10~15 行是什么样子的。所以我需要回到最后一次提交,并且能够回到我当前的代码而不提交它们。

标签: git

解决方案


使用git stash命令保存当前更改而不提交它们,并在以后返回它们。

从文档中:

Stashing 获取工作目录的脏状态——即修改后的跟踪文件和暂存的更改——并将其保存在未完成的更改堆栈中,您可以随时重新应用(即使在不同的分支上)

master以下是在分支上使用 stash 功能的示例用法:

1)说,有 2 个文件在最后一次提交中提交。

# Commit message: Adding file1.txt and file2.txt
file1.txt
file2.txt

2) 检查是否有任何内容要提交。

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working tree clean

3) 编辑file1.txt

$ vim file1.txt

4)现在,工作目录处于脏状态。

$ 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 checkout -- <file>..." to discard changes in working directory)

    modified:   file1.txt

5) 存储更改

$ git stash
Saved working directory and index state WIP on master: e1b8933 Adding file1.txt and file2.txt
HEAD is now at e1b8933 Adding file1.txt and file2.txt

6)查看file1.txt提交(即在本地修改之前)

$ cat file1.txt

7)查看存储列表

$ git stash list
stash@{0}: WIP on master: e1b8933 Adding file1.txt and file2.txt

8)从存储中恢复更改

$ git stash apply
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 checkout -- <file>..." to discard changes in working directory)

    modified:   file1.txt

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

推荐阅读