Git - Git教程 06:撤销修改

撤销修改

1 - 给 file_D.txt 文件添加内容 hello asshole !

复制代码
1 $ git status
2 On branch master
3 Changes not staged for commit:
4   (use "git add <file>..." to update what will be committed)
5   (use "git checkout -- <file>..." to discard changes in working directory)
6 
7     modified:   file_D.txt
8 
9 no changes added to commit (use "git add" and/or "git commit -a")
复制代码

2 - 撤销新添加的内容

1 $ git checkout -- file_D.txt

git checkout -- xxx 意思是把 xxx 文件在工作区的修改全部撤销,分两种情况

第一种:xxx 文件自修改后还没有被放到暂存区,这时撤销修改就回到和版本库一模一样的状态

第二种:xxx 文件 已添加到了暂存区且作了修改,这时撤销修改就回到添加到暂存区后的状态

总之它就是让这个文件回到最近一次 git commit 或 git add 时的状态

3 - 现在 file_D.txt 文件中添加内容 Asshole !!后,执行 git add 命令

1 git add file_D.txt

4 - 在没有 commit 前,我们查看状态

1 $ git status
2 On branch master
3 Changes to be committed:
4   (use "git reset HEAD <file>..." to unstage)
5 
6     modified:   file_D.txt

5 - Git 同样告诉我们,用命令 git reset HEAD file 可以把暂存区的修改撤销掉,重新放回工作区

1 $ git reset HEAD file_D.txt
2 Unstaged changes after reset:
3 M    file_D.txt

6 - 这时我们查看状态:暂存区是干净的,而工作区存在修改

复制代码
1 $ git status
2 On branch master
3 Changes not staged for commit:
4   (use "git add <file>..." to update what will be committed)
5   (use "git checkout -- <file>..." to discard changes in working directory)
6 
7     modified:   file_D.txt
8 
9 no changes added to commit (use "git add" and/or "git commit -a")
复制代码

7 - 丢弃工作区的修改,并查看状态

1 $ git checkout -- file_D.txt
2 $ git status
3 On branch master
4 nothing to commit, working tree clean

小结

1 - 假设你不但改错了东西,还从暂存区提交到了版本库,怎么办呢?版本回退啊,可以回退到上一个版本。不过,这是有条件的!就是你还没有把自己的本地版本库推送到远程。还记得 Git 是分布式版本控制系统吗?我们后面会讲到远程版本库,一旦你把新改动的内容 Asshole !!推送到远程版本库,那你就准备好纸巾使劲哭吧……

2 - 场景在线

① 场景A:当你改乱了工作区某个文件的内容,想直接丢弃工作区的修改时,用命令 git checkout -- fileName

② 场景B:当你不但改乱了工作区某个文件的内容,还添加到了暂存区时,想丢弃修改,分两步

    第一步用命令 git reset HEAD file 就回到了场景 A

    第二步重复场景 A 的步骤操作,即 git checkout -- fileName

③ 场景C:已经提交了不合适的修改到版本库时,想要撤销本次提交,就需要版本回退,前提是没有推送到远程库

posted on   低头捡石頭  阅读(16)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示