撤消 Git 中的更改
本教程介绍了撤消对本地和远程仓库所做更改的各种命令。这些命令包括:
git clean
git reset
git revert
使用 git log
命令检查 Git 中的提交历史
让我们首先看看我们如何检查我们的提交历史。我们使用 git log
命令检查这一点。
pc@JOHN MINGW64 ~/Git (main)
$ git log
commit 195e5c362975354d62ebc469da2e3cd276c7da03 (HEAD -> main)
Author: John <wachirajohnie11@gmail.com>
Date: Mon Feb 21 12:11:12 2022 +0300
commit 7b19db4b35c1ca15e5ecb8df1f805d44aad62e5f
Author: John <wachirajohnie11@gmail.com>
Date: Mon Feb 21 10:09:31 2022 +0300
first commit
该命令仅显示你的工作分支的历史记录。要检查所有分支,请使用以下命令。
git log --branches=*
使用 git checkout
命令查看特定的提交,如下所示。
现在你可以访问文件而不会篡改项目的当前状态。使用 git checkout main
命令返回到当前项目工作区。
使用 git clean
命令撤消 Git 中的更改
我们使用 git clean
命令撤消对未跟踪文件的更改。你无法撤消 git clean
命令。
-
git clean -n
选项充当试用命令。它只显示未跟踪的文件,但不会删除它们。例子:
pc@JOHN MINGW64 ~/Git (main) $ git clean -n Would remove Hello world.txt Would remove Test1.txt
-
git clean --force
命令删除工作目录中所有未跟踪的文件和文件夹。你可以使用.gitignore
命令抛出异常。例子:
pc@JOHN MINGW64 ~/Git (main) $ git clean --force Removing Hello world.txt Removing Test1.txt
让我们检查文件是否在我们的目录中。
pc@JOHN MINGW64 ~/Git (main) $ git status On branch main nothing to commit, working tree clean
输出显示一个干净的分支。该命令成功删除了文件。
使用 git revert
命令撤消 Git 中的更改
git revert
命令作用于提交所做的更改并覆盖它。我们用它来回到某个点并进行更改。
让我们使用命令来更改我们的 first commit
。
git revert first commit
#[first commit [7b19db4] Revert 'first commit'
#1 file changed, 1 deletion(-)
你必须通过提交参考。
使用 git reset
命令撤消 Git 中的更改
我们将介绍的最后一个命令是 git reset
。该命令在 HEAD
上运行。
-
git reset --hard
选项更改指定的提交。但是,暂存索引和工作目录中的任何更改都与更改相匹配。所有暂存的提交都会在此过程中丢失。例子:
$ git reset --hard HEAD is now at 78129a6 Revert "$first commit"
该命令对
HEAD
执行硬重置。 -
git reset --mixed
命令将临时索引中的更改保存到你的工作目录。例子:
$ git reset --mixed Unstaged changes after reset: M .bash_history M text.txt.txt M text.txt.txt.bak
该命令已将未完成的更改从输出中保存到我们的工作目录中。让我们检查一下我们分支的状态。
$ git status On branch main 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: .bash_history modified: text.txt.txt modified: text.txt.txt.bak Untracked files: (use "git add <file>..." to include in what will be committed) .bash_history.bak no changes added to commit (use "git add" and/or "git commit -a")
-
git reset --soft
命令仅更改提交历史记录。默认指针始终是HEAD
。例子:
pc@JOHN MINGW64 ~/Git (main) $ git reset --soft pc@JOHN MINGW64 ~/Git (main) $ git status On branch main 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: .bash_history modified: text.txt.txt modified: text.txt.txt.bak Untracked files: (use "git add <file>..." to include in what will be committed) .bash_history.bak no changes added to commit (use "git add" and/or "git commit -a")
从上面的输出中,我们的工作目录和暂存索引保持不变。使用提交的哈希值来重置特定的提交。