Git 的正确使用姿势与最佳实践 | 青训营

65 阅读2分钟

Git简介

git是一种版本控制工具,可以将代码上传托管至对应的仓库中

常用Git命令

创建版本库

首先创建版本库用于Git存放和管理要托管的代码

版本库又名仓库,英文名repository,你可以简单理解成一个目录,这个目录里面的所有文件都可以被Git管理起来,每个文件的修改、删除,Git都能跟踪,以便任何时刻都可以追踪历史,或者在将来某个时刻可以“还原”

在命令行中打开目标文件夹,使用git init把该文件夹设置为可管理的Git仓库

$ git init
Initialized empty Git repository in /Users/michael/learngit/.git/

出现第二行表示Git仓库建立成功,并且是一个空的仓库

添加文件

将文件放在版本库目录下,再通过git add和git commit提交到仓库中。

$ git add 文件名
$ git commit -m "本次提交说明"

git commit成功执行后会告诉你有多少文件被改动,改动的内容是什么

add和commit的不同处在于add只能添加一个文件,但commit可以添加多个文件

注意

  • 所有命令都必须在Git仓库内执行
  • 添加文件时,这个文件必须在仓库中

版本控制

文件查看

如果修改了文件,那么可以通过git status来查看仓库当前状况

$ 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:   readme.txt

no changes added to commit (use "git add" and/or "git commit -a")

可以告诉被修改的文件和提交状况;如果想了解修改的详细内容,可以通过git diff查看

$ git diff readme.txt 
diff --git a/readme.txt b/readme.txt
index 46d49bf..9247db6 100644
--- a/readme.txt
+++ b/readme.txt
@@ -1,2 +1,2 @@
-Git is a version control system.
+Git is a distributed version control system.
 Git is free software.

在这里可以看出在第一行添加了一个distributed单词,再进行内容添加并显示仓库状态,此时显示readme.txt将要被提交

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

	modified:   readme.txt

提交后再来看看仓库状况

$ git commit -m "add distributed"
[master e475afc] add distributed
1 file changed, 1 insertion(+), 1 deletion(-)

$ git status
On branch master
nothing to commit, working tree clean

此时显示仓库中没有文件需要提交、

版本回退

如果需要查看提交的过往内容,可以通过git log查看

$ git log
commit 1094adb7b9b3807259d8cb349e7df1d4d6477073 (HEAD -> master)
Author: Michael Liao <askxuefeng@gmail.com>
Date:   Fri May 18 21:06:15 2018 +0800

    append GPL

commit e475afc93c209a690c39c13a46716e8fa000c366
Author: Michael Liao <askxuefeng@gmail.com>
Date:   Fri May 18 21:03:36 2018 +0800

    add distributed

commit eaadf4e385e865d25c48e7ca9c8395c3f7dfaef0
Author: Michael Liao <askxuefeng@gmail.com>
Date:   Fri May 18 20:59:18 2018 +0800

    wrote a readme file

git log显示从最近到最远的提交日志,最近的一次是gpl,最远的是wrote a readme file