创建版本库
-
初始化仓库,使用
git init
-
使用命令
git add <file>
,注意,可反复多次使用,添加多个文件; -
使用命令
git commit -m <message>
,完成。 -
要随时掌握工作区的状态,使用
git status
命令。 -
如果
git status
告诉你有文件被修改过,用git diff
可以查看修改内容。
版本回退
-
HEAD
指向的版本就是当前版本,因此,Git 允许我们在版本的历史之间穿梭,使用命令git reset --hard commit_id
。 -
穿梭前,用
git log
可以查看提交历史,以便确定要回退到哪个版本。 -
要重返未来,用
git reflog
查看命令历史,以便确定要回到未来的哪个版本 -
用
git diff HEAD -- readme.txt
命令可以查看工作区和版本库里面最新版本的区别
撤销操作
-
当你改乱了工作区某个文件的内容,想直接丢弃工作区的修改时,用命令
git checkout -- file
。 -
当你不但改乱了工作区某个文件的内容,还添加到了暂存区时,想丢弃修改,分两步,第一步用命令
git reset HEAD <file>
,就回到了上面,第二步按上面的步骤。 -
已经提交了不合适的修改到版本库时,想要撤销本次提交,参考版本回退,不过前提是没有推送到远程库
删除文件
一般情况下,你通常直接在文件管理器中把没用的文件删了,或者用rm命令删了:
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
:
$ git rm test.txt
rm 'test.txt'
$ git commit -m "remove test.txt"
[master d46f35e] remove test.txt
1 file changed, 1 deletion(-)
delete mode 100644 test.txt
现在,文件就从版本库中被删除了。
创建与合并分支
Git 鼓励大量使用分支:
-
查看分支:
git branch
-
创建分支:
git branch <name>
-
切换分支:
git checkout <name>
或者git switch <name>
-
创建+切换分支:
git checkout -b <name>
或者git switch -c <name>
-
合并某分支到当前分支:
git merge <name>
-
删除分支:
git branch -d <name>