一、什么是版本库(Repository)?
版本库(也叫"仓库")是 Git 用来管理项目文件及其所有修改历史的地方。
你可以把它想象成一个智能文件夹:
- 你在这个文件夹里写代码、改文档、删文件......
- Git 会默默记录每一次变化。
- 如果哪天你发现"还是上周的版本更好",就能轻松回退到任意历史状态,甚至查看某次具体改了哪些内容。
举个例子:就像你写作文反复修改,Git 能帮你保存每一个草稿,并随时找回"最满意的那一版"。
这个被 Git 管理的文件夹,就是版本库。
二、安装 Git(Ubuntu)
我们以 Ubuntu 系统为例进行操作。
首先,检查是否已安装 Git:
css
git --version
如果已安装,你会看到类似输出:
git version 2.52.0
如果未安装,执行以下命令安装:
sql
sudo apt update
sudo apt install git
三、配置 Git 用户信息
Git 需要知道你是谁,以便在提交记录中标注作者。只需配置一次:
arduino
git config --global user.name "Your Name"
git config --global user.email "email@example.com"
这里的邮箱不一定要真实,但建议与 GitHub/GitLab 账号一致,方便关联。
四、创建你的第一个版本库
- 创建一个新目录作为项目根目录(位置随意):
bash
mkdir learngit
cd learngit/
pwd
输出示例:
bash
/home/user/Desktop/learngit
- 将该目录初始化为 Git 仓库:
csharp
git init
成功后会提示:
bash
Initialized empty Git repository in /home/user/Desktop/learngit/.git/
- 查看隐藏文件:
bash
ls -la
你会看到一个名为 .git 的隐藏目录:
. .. .git
重要 :
.git是 Git 的核心数据库,千万不要手动修改或删除它!否则版本历史将丢失。
五、添加文件并提交到版本库
我们在 learngit 目录下创建一个 C++ 源文件 hello.cpp:
c
#include <iostream>
using namespace std;
int main(void) {
cout << "Hello World!" << endl;
return 0;
}
确保文件保存在
learngit/目录内,这样它才属于当前工作区。
1. 查看当前状态
lua
git status
输出:
vbnet
On branch master
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
hello.cpp
nothing added to commit but untracked files present (use "git add" to track)
说明:
- 当前在
master分支(Git 默认主分支名) - 仓库尚未有任何提交
hello.cpp是一个未被跟踪的新文件
2. 将文件加入暂存区
使用 git add 告诉 Git:"我想把这个文件纳入下一次提交":
csharp
git add hello.cpp
再次运行 git status:
vbnet
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: hello.cpp
现在 hello.cpp 已进入暂存区,准备被正式提交。
3. 提交到版本库
执行提交命令,并附上简明的说明:
sql
git commit -m "wrote hello world source file"
输出示例:
scss
[master (root-commit) 7d2e3bf] wrote hello world source file
1 file changed, 8 insertions(+)
create mode 100644 hello.cpp
至此,你的第一个版本已成功保存!
master:当前分支7d2e3bf:本次提交的唯一 ID(可用来回溯)1 file changed:本次提交包含 1 个文件,新增 8 行代码
六、小结
| 步骤 | 命令 | 作用 |
|---|---|---|
| 初始化仓库 | git init |
创建本地版本库 |
| 查看状态 | git status |
了解文件跟踪情况 |
| 添加文件 | git add <file> |
将文件放入暂存区 |
| 提交变更 | git commit -m "说明" |
正式保存一个版本 |