Git中文社区

创建与克隆仓库

获取 Git 仓库通常有两种方式:一是把本地一个尚未进行版本控制的目录转换为 Git 仓库;二是从其他服务器克隆一个已存在的 Git 仓库。

在已有目录中初始化仓库

进入项目目录,执行 git init:

mkdir my-project
cd my-project
git init
# Initialized empty Git repository in /home/zhangsan/my-project/.git/

该命令会在当前目录下创建一个名为 .git 的隐藏子目录,其中包含初始化仓库所需的所有文件。此时仓库还是空的,没有任何文件被跟踪。

也可以直接指定目录名,Git 会自动创建目录:

git init my-project

如果想指定初始分支名:

git init -b main

完成第一次提交

echo "# 我的项目" > README.md
git add README.md
git commit -m "初始化项目"

执行 git log 就能看到这次提交。

克隆现有仓库

如果想获取一份已经存在的 Git 仓库(比如参与某个开源项目),使用 git clone:

git clone https://github.com/git/git.git

这会在当前目录下创建一个名为 git 的目录,并在其中初始化 .git 文件夹,拉取远程仓库的全部数据,然后检出最新版本的工作副本。

自定义本地目录名

git clone https://github.com/git/git.git my-git

支持的协议

Git 支持多种传输协议:

协议示例说明
HTTPShttps://github.com/user/repo.git最通用,推送时需要令牌认证
SSH[email protected]:user/repo.git配置密钥后免密推送,推荐
Gitgit://example.com/repo.git只读、无认证,已较少使用
本地/srv/git/repo.git 或 file:///srv/git/repo.git同一台机器或共享目录

加速克隆大型仓库

对于历史非常长的仓库,如果只需要最新代码,可以使用浅克隆:

# 只克隆最近 1 次提交
git clone --depth 1 https://github.com/torvalds/linux.git

# 只克隆指定分支
git clone --branch dev --single-branch https://github.com/user/repo.git

之后如果需要完整历史,可以再补全:

git fetch --unshallow

也可以使用部分克隆,先不下载文件内容,用到时再按需获取:

git clone --filter=blob:none https://github.com/user/repo.git

提示

国内克隆 GitHub 仓库较慢时,可以先把仓库导入到 Gitee 再克隆,或者为 Git 配置代理(见"初次配置"一章)。

裸仓库

服务器上用于共享的仓库通常是裸仓库(bare repository),它没有工作区,只有 .git 目录中的内容:

git init --bare project.git
git clone --bare https://github.com/user/repo.git

裸仓库不能直接在里面编辑文件,只用来被推送和拉取。