📦 归档笔记 — 原创建于 WizNote,仅作归档展示;观点以当年为准,非最新。

Git学习日志

创建时间2019-04-23最后修改2019-04-24原位置/程序员成长之旅/Linux学习/字数824
目录:程序员成长之旅/Linux学习

Git学习日志

Git基本配置

git config --global user.name "Your Name"
git config --global user.email "email@example.com"

其中--global表示这台机器上所有的Git仓库都会使用这个配置

Git初始化(创建)

cd /xx/xxx#进入目录
git init#初始化一个(创建)一个仓库

可以使用ls -al 观察到该目录下有一个.git目录

Git添加文件

创建了某些文件时

#添加文件
git add file.xx
git add xxx.c
git add test.java
#提交文件(可以一次性提交多个文件)
git commit -m "add 3 files."# -m 后面是提交文件的说明

Git的修改文件

当我们修改了某些文件或者对仓库状态未知时

git status #掌握工作区状态 得知哪些文件被改动
git diff fileName.xx # 查看某个文件的改动

在确认无误的情况下提交文件

git add fileName.xx 
git commite -m "del xxx"

再次检查仓库状态

git status

应得回显

root@izbp11iqplyxdovikmbnimz ~/testGit# git status 
# On branch master
nothing to commit, working directory clean

则仓库为没有需要提交的更改,且工作目录干净(working directory clean)

Git的历史版本(版本回退)

有的时候我们对自己的修改并不满意的时候,怎么办呢?

这个时候就可以使用Git的版本回退功能

首先查询共有多少个提交历史记录

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

加入 --pretty=oneline 参数可以简短的显示历史记录

例如我们现在提交了三个版本的readme.txt 现在想要回到上一个版本应该怎么做?

git reset --hard HEAD^ #回到上一个版本
get reset --hard HEAD^^ #回到上上的版本
get reset --hard HEAD~100 #回到上100个版本

你很满意的回到了上一个版本,但是你又突然后悔了!

你慌张的尝试用git log 查看历史记录,发现第三个版本不见了!!

不要慌,使用 git reflog 查看操作记录

git reflog
e475afc HEAD@{1}: reset: moving to HEAD^
1094adb (HEAD -> master) HEAD@{2}: commit: append GPL
e475afc HEAD@{3}: commit: add distributed
eaadf4e HEAD@{4}: commit (initial): wrote a readme file
git reset --hard 1094adb #穿越到第三个版本

另外:Git的版本回退速度非常快,因为Git在内部有个指向当前版本的HEAD指针,当你回退版本的时候,Git仅仅是把HEAD从指向append GPL:

┌────┐ │HEAD│ └────┘ │ └──> ○ append GPL │ ○ add distributed │ ○ wrote a readme file

改为指向add distributed:

┌────┐ │HEAD│ └────┘ │ │ ○ append GPL │ │ └──> ○ add distributed │ ○ wrote a readme file

小结

现在总结一下:

  • HEAD指向的版本就是当前版本,因此,Git允许我们在版本的历史之间穿梭,使用命令git reset --hard commit_id。
  • 穿梭前,用git log可以查看提交历史,以便确定要回退到哪个版本。
  • 要重返未来,用git reflog查看命令历史,以便确定要回到未来的哪个版本。

来源:https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000/0013744142037508cf42e51debf49668810645e02887691000