初始化项目
git init

如图所示,在 gitSpace
文件目录下会生成一个 .git
的隐藏文件夹,这个目录中存放的是本地库相关的子目录和文件,我们不要将这个文件夹删除或者做任何修改。
通常,在 git
安装完成后,需要设置签名以区分不同开发人员的身份。通常需要设置用户名 user.name
以及邮箱 user.email
两个字段。
# 将用户名和密码换成你自己的
git config --global user.name panjian
git config --global user.email panjianmails@foxmail.com
因为我们设置的是全局的配置,所以可以在 ~/.gitconfig
里面可以看到我们刚才的配置:

如果没有 --global
这个参数,则是对该项目(这里是 gitSpace)进行设置,可以在 .git/config
文件下查看我们刚才的配置。
查看状态
git status

因为现在还没有进行任何操作,所以提示我们无文件要提交。

上面的图片中,我们向 test.txt
文件写入了 test git status!
,然后使用 git status
查看现在的状态,发现提示变成了使用 "git add <文件>..."。因此,在我们不知道下一步该怎么进行 git 操作的时候,这个命令可以给予我们很大的帮助。
将文件提交早暂存区
# 提交全部文件
git add .
# 提交制定文件 git add <文件名>
git add test.txt

下面我们可以使用 git rm --cached <文件>...
恢复成 git add
之前的样子或者使用 git commit
向本地库提交。

提交到本地库
git commit -m "提交信息"

在进行 commit 操作之前需要将文件添加到暂存区。
如果对文件进行了修改,我们再来查看当前文件的状态:

提示我们文件做出了修改,只需要重新 git add——>git commit
就可以更新本地库的 test.txt 文件了。
总结下来,就是下面这个图的样子:

版本的前进和后退
在进行版本的前进和后退之前,得先了解 git log
命令,这个命令就是用来查看我们的提交记录的。
图上面的
HEAD ——> master
表示当前的版本为6d068e6
开头的这个版本。

可以看到,通过 git log
命令,我们能够看到我们提交的每一次修改。或者使用 git log --pretty=oneline
和 git log --oneline
查看日志信息(上:git log --pretty=oneline。下:git log --oneline)。


还有一种办法,就是使用 git reflog
来查看:

图中的 HEAD@{1}
表示回退一步就能退回到该版本,当然 HEAD@{2}
就是两步了,对于帮助我们实现版本前进和后退非常有用。
基于索引值的前进和后退
# 03522d7 就是我们查看日志时最前面的哈希值
git reset --hard 03522d7

使用^回退(只能回退)
# HEAD 后面几个 ^ 就回退几个版本
git reset --hard HEAD^
使用~回退(只能回退)
# ~ 后面的数字表示回退的版本数,为 1 表示回退到上个版本,可以与 git reflog 结合使用
git reset --hard HEAD~1
hard、soft 以及 mixed 的区别
上面我们使用到了 --hard
这个参数,下面我们来解释一下:
- --soft: 仅在本地库移动 HEAD 指针

-
--hard: 三个库全部重置
-
--mixed(默认): 在本地库移动指针,重置暂存区

删除文件后找回
前提:删除前,文件已经提交到了本地库。

现在我们将本地的文件删除并提交:

只需要回退到没有删除该文件的版本就可以找回删除的文件了。

可以看到 delete.txt
文件已经找回了。
文件比较
-
git diff [文件名]: 将本地库中的文件和暂存区进行比较
git diff test.txt

-
git diff [本地库中历史版本] [文件名]: 将本地库中的文件和本地库历史记录比较
git diff HEAD^ test.txt

-
git diff: 不带文件名比较多个文件
git diff

分支
创建分支
git branch [分支名]
查看分支
git branch -v

切换分支
git checkout [分支名]
对 dev 分支的文件修改提交后,可以看到 dev 分支的 commit 信息改变了而 master 还是原来的 删除文件测试
。

合并分支

最后我们使用 git branch -v
查看当前分支情况,合并成功:

网友评论