销修改就回到和版本库一模一样的状态
new.py
自修改后还没有被放到暂存区,现在,撤销修改就回到和版本库一模一样的状态;
- new.py已经添加到暂存区后,又作了修改,现在,撤销修改就回到添加到暂存区后的状态;
② 已经提交到暂存区的文件撤销
不但修改了代码,而且还add存放到缓存区了:
[root@localhost spider]# more new.py
#create new file
second commit
third commit
Git tracks changes of files.
My stupid boss still prefers SVN.
[root@localhost spider]# git add new.py
庆幸的是,在commit
之前,你发现了这个问题。用git status
查看一下,修改只是添加到了暂存区,还没有提交:
[root@localhost spider]# git status
# 位于分支 master
# 要提交的变更:
# (使用 "git reset HEAD <file>..." 撤出暂存区)
#
# 修改: new.py
Git同样告诉我们,用命令git reset HEAD file
可以把暂存区的修改撤销掉(unstage),重新放回工作区:
[root@localhost spider]# git reset HEAD new.py
重置后撤出暂存区的变更:
M new.py
[root@localhost spider]# git status
# 位于分支 master
# 尚未暂存以备提交的变更:
# (使用 "git add <file>..." 更新要提交的内容)
# (使用 "git checkout -- <file>..." 丢弃工作区的改动)
#
# 修改: new.py
#
修改尚未加入提交(使用 "git add" 和/或 "git commit -a")
再次执行git checkout -- <file>,恢复到最初:
[root@localhost spider]# git checkout -- new.py
[root@localhost spider]# git status
# 位于分支 master
无文件要提交,干净的工作区
注:这里所有的撤销都是指代码未提交到仓库时的撤销
6、删除操作
在Git中,删除也是一个修改操作,我们实战一下,先添加一个新文件test.txt到Git并且提交:
$ git add .
$ git commit -m "add test.txt"
[master a8fa95a] add test.txt
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 test.txt
一般情况下,你通常直接在文件管理器中把没用的文件删了,或者用rm
命令删了
[root@localhost spider]# rm test.txt
这个时候,Git知道你删除了文件,因此,工作区和版本库就不一致了,git status
命令会立刻告诉你哪些文件被删除了:
$ git status
On branch master
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
deleted: test.txt
no changes added to commit (use "git add" and/or "git commit -a")
现在你有两个选择,一是确实要从版本库中删除该文件,那就用命令git rm
删掉,并且git commit
:
x$ git rm test.txt
rm 'test.txt'
$ git commit -m "remove test"
[master 03df00a] remove test
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 test.txt
现在,文件就从版本库中被删除了。
另一种情况是删错了,因为版本库里还有呢,所以可以很轻松地把误删的文件恢复到最新版本:
[root@localhost spider]# git checkout -- test.txt
git checkout
其实是用版本库里的版本替换工作区的版本,无论工作区是修改还是删除,都可以“一键还原”。
7、删除远程文件
假如远程文件index.html是多余文件,需要把他删除,如何做?
# 先把本地文件进行删除,查看git状态
[root@localhost spider]# rm index.html
rm:是否删除普通文件 "index.html"?y
[root@localhost spider]# git status
# 位于分支 master
# 尚未暂存以备提交的变更:
# (使用 "git add/rm <file>..." 更新要提交的内容)
# (使用 "git checkout -- <file>..." 丢弃工作区的改动)
#
# 删除: index.html
#
修改尚未加入提交(使用 "git add" 和/或 "git commit -a")
用git rm清除刚刚删除的文件,上传更新:
[root@localhost spider]# git rm index.html
rm 'index.html'
[root@localhost spider]# git commit -m 'rm index.html'
[master c54c7fe] rm index.html
1 file changed, 2 deletions(-)
delete mode 100644 index.html
[root@localhost spider]# git push -u origin master
bbaa116..99c5dfe master -> master
查看远程代码库,文件index.html文件已经删除
8、忽略文件
有些时候,你必须把某些文件放到Git工作目录中,但又不能提交它们,比如保存了数据库密码的配置文件啦,等等,每次git status
都会显示Untracked files ...
,有强迫症的童鞋心里肯定不爽。好在Git考虑到了大家的感受,这个问题解决起来也很简单,在Git工作区的根目录下创建一个特殊的.gitignore
文件,然后把要忽略的文件名填进去,Git就会自动忽略这些文件。不需要从头写.gitignore
文件,GitHub已经为我们准备了各种配置文件,只需要组合一下就可以使用了。所有配置文件