玖叶教程网

前端编程开发入门

Git 必知必会(git详细教程)

上一篇文章已经介绍了Git 的基本使用方法,本篇文章我们继续学习强大的Git 命令来维护我们的项目代码。上一篇中项目是从现存的Git 库中clone过来的,这次我们将新构建一个项目,从最初开始。


命令之一:git init

git init 命令可以在目录中创建新的 Git 仓库
$ mkdir test_project
$ cd test_project/
$ ll -a
total 12
drwxr-xr-x 1 tdcengineer 197121 0 8月 2 14:54 ./
drwxr-xr-x 1 tdcengineer 197121 0 8月 2 14:54 ../
执行完成git init 后:
$ git init
Initialized empty Git repository in C:/Users/tdcengineer/test_project/.git/
tdcengineer@DESKTOP-U4OR066 MINGW64 ~/test_project (master)
$ ls -a
./ ../ .git/
现在你可以看到在你的项目中生成了 .git 这个子目录。 这就是你的 Git 仓库了,所有有关你的此项目的快照数据都存放在这里。


命令之二:git diff

你可以执行 git diff 来查看执行 git status 的结果的详细信息。


git diff 命令显示已写入缓存与已修改但尚未写入缓存的改动的区别。git diff 有两个主要的应用场景。


尚未缓存的改动:git diff
查看已缓存的改动:git diff --cached
$ touch test.py #创建文件
$ git add test.py #添加到git管理
$ cat test.py #编辑文件后查看
print("hello wolrd")
print("good job")
$ git diff
warning: LF will be replaced by CRLF in test.py.
The file will have its original line endings in your working directory
diff --git a/test.py b/test.py
index e69de29..6b24a88 100644
--- a/test.py
+++ b/test.py
@@ -0,0 +1,2 @@
+print("hello wolrd")
+print("good job")
git diff 后test.py 文件在之前是空文件,之后是我填写了内容的文件,非常详细的对比展示出来了。


我再添加一个abc.py 的文件,来演示--cached 的使用场景:
$ git diff --cached
diff --git a/abc.py b/abc.py
new file mode 100644
index 0000000..2a64674
--- /dev/null
+++ b/abc.py
@@ -0,0 +1,2 @@
+for i in range(1999):
+ print("good")
diff --git a/test.py b/test.py
new file mode 100644
index 0000000..e69de29


命令之三:git mv

使用git mv 命令用于移动或重命名一个文件、目录、软连接
$ git mv abc.py a.py
$ ls -a
./ ../ .git/ a.py test.py


命令之四:git rm

从所在的工作目录中手工删除文件,-f表示强制删除,与linux 下命令是一致的。
$ ls -a #temp.py 文件是新增的
./ ../ .git/ a.py temp.py test.py
$ git rm -f temp.py #强制删除temp.py 文件
rm 'temp.py'


命令之五:git branch

在代码维护过程中,我们的要来维护不断的分支的,不同的需求代码会在不断的分支上面开发,那么我们就需要会创建自己的分支。
git branch branchname 就可以创建分支
$ git branch fixbug-0802
使用 git checkout -b (branchname) 命令来创建新分支并立即切换到该分支下,从而在该分支中操作
使用 git branch -d (branchname)命令来删除分支


$ git branch #列出当前仓库有什么分支
fixbug-0802
* master


命令之六:git checkout

我们也可以用 git checkout (branch) 切换到我们要修改的分支
$ git branch fixbug-0802
$ echo "abc123" > b.txt 在fixbug分支下创建一个b.txt
$ git add b.txt . 添加到分支上
$ git commit -m "good" #在该分支上提交一下


$ git checkout master #表示切换到master 分支下
$ ls #只看到了两个文件
a.py test.py


$ git checkout fixbug-0802 #切换到fixbug分支下
Switched to branch 'fixbug-0802'
$ ls #多出来了一个文件b.txt 
a.py b.txt test.py


命令之七:git merge

我们在独立分支上开发的内容,你终究会希望将它合并回到你的主分支。
$ git merge fixbug-0802 master
Updating f88c2b9..f55fa51
Fast-forward
b.txt | 1 +
test.py | 2 ++
2 files changed, 3 insertions(+)
create mode 100644 b.txt


$ ls   #b.txt 文件被合并过来了
a.py b.txt test.py


备注:合并不是简单的文件添加,删除操作,git 也会做合并修改,如果出现冲突了,需要人工介入处理。


命令之八:git tag

有时候我们的项目达到一个重要的阶段,并希望永远记住那个特别的提交快照,你可以使用 git tag 给它打上标签。
$ git tag -a v1.0  #当你执行 git tag -a 命令时,Git 会打开你的编辑器,让你写一句标签注解,就像你给提交写注解一样。
现在,注意当我们执行 git log --decorate 时,我们可以看到我们的标签了


$ git tag #查看现有的tag信息
v1.0

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言