Git Learning 1


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

所以,创建一个版本库非常简单,首先,选择一个合适的地方,创建一个空目录:

$ mkdir learngit
$ cd learngit
$ pwd
/Users/michael/learngit

第二步,通过 git init 命令

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

创建成功后,当前目录下会多一个  .git 目录, 如果没有发现,那是因为这个目录默认是隐藏的,用下面命令,就可以看见

ls -ah

 首先,这里明确一下,所有的版本控制系统其实只能跟踪文本文件的改动,比如TXT文件,网页,所有程序代码等等。Git也不例外。而图片、视频这些二进制文件,虽然也能由版本控制系统股那里,但没有办法跟踪文件的变化,只能把二进制文件每次改动串起来,也就是只知道图片从100KB改成了120KB,但到底改了啥,版本控制系统不知道,也没法知道。

不幸的是,Microsoft 的 word 格式是二进制格式,因此,版本控制系统是没办法跟踪 word文件的改动的。

言归正传,现在我们编写一个readme.txt 文件,内容如下

Git is a version control system.
Git is free software.

把一个文件放到 Git 仓库,只需要两步

第一步, 用命令 git add 告诉 Git , 把文件添加到仓库:

git add readme.txt

执行上面的命令,没有任何显示,这就对了,Unix的哲学是“没有消息就是好消息”,说明添加成功。

第二步,用命令 git commit 告诉Git ,把文件提交到仓库:

$ git commit -m "wrote a readme file"
[master (root-commit) eaadf4e] wrote a readme file
 1 file changed, 2 insertions(+)
 create mode 100644 readme.txt
PS C:\learningGit> git commit -m "git learning1"
[master (root-commit) 9b970b1] git learning1
 Committer: Cristiano Zhao (赵文志) 
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly. Run the
following command and follow the instructions in your editor to edit
your configuration file:

    git config --global --edit

After doing this, you may fix the identity used for this commit with:

    git commit --amend --reset-author

 1 file changed, 2 insertions(+)
 create mode 100644 readme.tx

简单的解释一下 git commit 命令, -m 后面输入的是本次提交的说明,可以输入任意内容,当然最好是有意义的,这样你就能从历史记录里方便地找到改动记录。

git commit命令执行成功后会告诉你, 1 file changed: 1个文件被改动(我们新添加的 readme.txt文件); 2 insertions:插入两行内容(readme.txt有两行内容)

为什么Git 添加文件需要 add , commit 一共两步呢?因为 commit 可以一次提交很多文件,所以你可以多次 add 不同的文件,比如:

$ git add file1.txt
$ git add file2.txt file3.txt
$ git commit -m "add 3 files."

疑难解答

Q:输入 git add readme.txt,得到错误:fatal: not a git repository (or any of the parent directories)

A:Git命令必须在Git仓库目录内执行( git init 除外),在仓库目录外执行是没有意义的。

Q:输入 git add readme.txt,得到错误fatal: pathspec 'readme.txt' did not match any files

A:添加某个文件时,该文件必须在当前目录下存在,用 ls 或者 dir 命令查看当前目录的文件,看看文件是否存在,或者是否写错了文件名。

现在总结一下这篇的两点内容:

初始化一个Git仓库,使用 git init 命令。

添加文件到Git仓库,分两步:

  1. 使用命令 git add ,注意,可反复多次使用,添加多个文件;
  2. 使用命令 git commit -m ,完成。
Git