53

Git 撤销所有未提交(Commit)的内容

 5 years ago
source link: https://shockerli.net/post/git-undo-uncommit-content/?amp%3Butm_medium=referral
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.

撸了好多代码,但是突然设计改了(~~o(>_<)o ~~);或者引入个第三方库,后来又发现用不着,想删掉,但文件太多了(比如几百个);那,怎么办呢,都不想了…Git 比人聪明,所以能很方便的帮我们解决问题。

场景一

需要撤销的内容文件属于未跟踪的状态。如下命令产生的场景:

mkdir git-tmp
cd git-tmp
git init
echo '第1次输入的内容' > file1.log
git status

以上命令产生了 file1.log 文件,该文件未被执行过 git add 、也不在版本库中。清除此类未被跟踪的文件:

git clean -fdx

场景二

需要撤销的内容已被 git add 暂存,但未执行 git commit 提交。如下命令产生的场景:

mkdir git-tmp
cd git-tmp
git init
echo '第1次输入的内容' > file1.log
git add .
git status

那么执行以下命令即可取消文件的暂存:

git rm --cached -r .

或者,使用:

git reset

也可以取消所有文件的暂存。

然后,我们再执行 git clean -fdx 清除文件。

场景三

已提交在版本库中的文件发生了变更、但修改的内容未暂存。如下命令产生的场景:

mkdir git-tmp
cd git-tmp
git init
echo '第1次输入的内容' >> file1.log
git add .
git commit -m '第1次提交'
echo '第2次输入的内容' >> file1.log
git status

这种情况,我们可用:

git checkout .

就可以清除所有变更内容。

场景四

已在版本库中的文件发生了变更、且已 git add 暂存。如下命令产生的场景:

mkdir git-tmp
cd git-tmp
git init
echo '第1次输入的内容' >> file1.log
git add .
git commit -m '第1次提交'
echo '第2次输入的内容' >> file1.log
git add .
git status

这种情况,比场景三仅多了步暂存,那我们可以先取消暂存、然后再检出:

git reset
git checkout .

也就是场景二和场景三的混合情况。

总结

我们以上所有场景都是内容未被提交(commit)的情况下。如果是撤销提交操作,那就是其他方法了。

基于以上,我们发现,如果对于已修改的所有内容,我们都不想要了,想回到最干净的上个提交版本的状态。那么,3个命令就可以搞定一切:

git reset
git checkout .
git clean -fdx

最后,再说个小白都能解决该类问题的工具 —— SourceTree ,自行尝试吧。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK