Git 教程 - 初始化本地仓库

Jinku Hu 2022年2月6日
Git 教程 - 初始化本地仓库

我们将在本教程中创建我们的第一个 git 项目。

你可以在 C 盘创建一个文件夹 Git,但此 C:\Git 文件夹绝对不是必需的步骤,只是我个人习惯将所有的本地仓库该文件夹中。

然后,我们在 C:\Git 文件夹中创建一个 GitLearn 新文件夹,这将是我们在本教程中演示用的项目文件夹。

我们可以用 git init 在这个文件夹初始化空的 git 仓库,

$ git init 

然后我们在 git bash 中会看到成功的初始化确认信息。

$ git init
Initialized empty Git repository in C:/Git/GitLearn/.git/

git status

在我们开始在仓库中添加文件之前,我们可以用 git status 来获取仓库的当前状态。

$ git status
On branch master

No commits yet

nothing to commit (create/copy files and use "git add" to track)

的确,仓库仍然是空的,它还没有任何的提交。

那么我们可以在这个文件夹中添加一些文件,比如新建一个 test1.txt 文件并且把下面的内容加入到文件中,

This is my first Git repository.

如果再次用 git status 检查,将会得到

$ git status
On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	test1.txt

nothing added to commit but untracked files present (use "git add" to track)

新文件显示在未跟踪文件列表中的状态信息中。如果我们不添加和提交它们,Git 就不会跟踪未跟踪的文件。

我们首先需要使用 git add 命令将它们添加到 staging 区域,也就是暂存区。

git add test1.txt

现在,再次用 git status 来查询最新的工作区状态。

$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

	new file:   test1.txt

添加的文件现在位于暂存区中并等待提交。你现在可以应该使用 git commit 命令将新的在暂存区的文件 test1.txt 提交到仓库中。

$ git commit -m "the first commit. add test1.txt to the repository"
[master (root-commit) 15322c9] the first commit. add test1.txt to the repository
 1 file changed, 1 insertion(+)
 create mode 100644 test1.txt

这时如果你检查工作区的状态,将会看到干净的工作树信息,没有文件有变化或未被跟踪。

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

如果你要获取提交历史记录的日志记录信息,可以使用 git log 来检索已经提交的日志。

$ git log
commit 15322c93a528af85dbba478a77b93cb6477698cb
Author: Your Name <yourname@email.com>
Date:   Wed Jul 25 00:14:49 2018 +0200

    the first commit. add test1.txt to the repository
作者: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

DelftStack.com 创始人。Jinku 在机器人和汽车行业工作了8多年。他在自动测试、远程测试及从耐久性测试中创建报告时磨练了自己的编程技能。他拥有电气/电子工程背景,但他也扩展了自己的兴趣到嵌入式电子、嵌入式编程以及前端和后端编程。

LinkedIn Facebook