Fork me on GitHub

现在添加一个新的文件 t.c, 写一行 int a;
git add . 添加跟踪,当前状态

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
        new file:   t.c

括号提示用 git reset HEAD ... 移除跟踪的文件,这和前面一文提到的 git rm --cached ... 是一样的作用,只是选项不一样都可以取消文件的跟踪,运行命令

$ git rm --cached t.c
rm 't.c'
$ git add .
$ git reset HEAD t.c
$ git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)
        t.c
nothing added to commit but untracked files present (use "git add" to track)

这两个命令可以移除不需要跟踪的文件,而重新出现在工作区中,等待 add ,然而一个工程里会有很多不需要跟踪和记录的文件,比如:编译器自动生成的临时文件,文件很大,一些第三方的代码可以很方便的获取到等,怎么彻底地移除这些文件?
Git 提供了一个忽略文件,.gitignore 全名,在此文件中出现的文件不会被仓库记录,这个文件支持正则匹配,这里用个 windows 下 visual studio 工程的 .gitignore 文件(这个文件是在 GitHub 上新建远程仓库提供的范例,自己的可以按需要来写)

现在把 t.c 提交

$ git commit -a -m "add t.c"
[master 72daeee] add t.c
 1 file changed, 1 insertion(+)
 create mode 100644 t.c

然后在文件中添加一行 int b;, 查看此时的状态

$ git status
On branch 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:   t.c
no changes added to commit (use "git add" and/or "git commit -a")

这时,我感到刚才的修改毫无意义,我怎么把刚才的修改撤消,!注意这是个危险的操作,它会修改你的源文件,执行这个命令前必须清楚你在做什么,你对这个文件的修改会被撤消,回到上次提交的状态,这里我, 确实不需要这次修改

$ git checkout  -- t.c
$ cat t.c
int a;

这样文件的修改就没有了,!注意 这是一个危险的操作

好吧! 我又反悔了,重新在 t.c 中加上一行 int b;,不过又不想再提交一次 update, 这样就多一次不怎么重要的提交,下面这个命令可以做到,先看下简单的提交历史

$ git log --pretty=format:"%h -- %cn -- %s"
72daeee -- H•K -- add t.c
9201c98 -- H•K -- update readme.md
2e07671 -- H•K -- first commit

接下来添加更改跟踪

$ git add .
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
        modified:   t.c

然后再提交的时候加上选项 --amend ,这时 Git 会打开 vim 编辑上次的提交信息,像这样:
git commit amend
其实也不用修改什么直接按住 shift 键,连按两次 z,退出就好了,

$ git commit --amend
[master e335514] add t.c
 1 file changed, 2 insertions(+)
 create mode 100644 t.c

上次的提交就修改了,看下状态和历史:

$ git status
On branch master
nothing to commit, working directory clean
$ git show
commit e3355146dc3917d58ca1a8caeae53aadf5f451e8
Author: H•K <H-k_@outlook.com>
Date:   Tue Sep 1 17:12:18 2015 +0800
    add t.c
     On branch master
     Changes to be committed:
        new file:   t.c
     Changes not staged for commit:
        modified:   t.c
diff --git a/t.c b/t.c
new file mode 100644
index 0000000..dc904e7
--- /dev/null
+++ b/t.c
@@ -0,0 +1,2 @@
+int a;
+int b;
$ git log --format="%h -- %cn -- %s"
e335514 -- H•K -- add t.c
9201c98 -- H•K -- update readme.md
2e07671 -- H•K -- first commit

git show 显示最近一次提交详情

可以看到提交没有明显变化,文件重新修改的内容已经记录了

Git 的撤消操作大多是针对仓库记录的信息,整理好提交的信息,便于对仓库的维护,尤其是大型的仓库。少数操作会修改文件,即可以撤消单个文件的修改,也可以撤消整个仓库记录的文件,撤消只是单纯用以前的文件覆盖当前的文件,在那之前的修改都会被还原,所以这些操作是危险的,执行前一定要想好。

posted on 2015-09-01 19:15  H·K  阅读(219)  评论(0编辑  收藏  举报