Skip to content

Git - 在线仓库

像 GitHub、GitLab 和 Bitbucket 这样的平台提供基于 Web 的 Git 仓库 托管服务,以及协作、问题跟踪等功能。本节重点介绍如何使用命令行与 GitHub 仓库 进行交互。

  1. 访问 GitHub。
  2. 登录您的账户或创建一个新账户。
  3. 点击导航栏中的“New”按钮或“+”图标来创建新 仓库。按照屏幕上的说明操作,为您的 仓库 命名(例如 my_first_repo)。您可以选择使用 README、.gitignore 和 license 初始化它。

Tom 有一个现有的本地 Git 项目,并希望将其托管在 GitHub 上。首先,他在 GitHub 上创建一个新的空 仓库(例如命名为 hello_world_project),不使用 README、.gitignore 或 license 初始化它,因为他的本地项目已经有自己的历史了。

Tom 有一个包含 hello.c 文件的本地项目:

[tom@devbox ~]$ mkdir hello_world_project
[tom@devbox ~]$ cd hello_world_project/
[tom@devbox hello_world_project]$ echo '#include <stdio.h>
int main() {
printf("Hello, Modern Git!\n");
return 0;
}' > hello.c
[tom@devbox hello_world_project]$ gcc hello.c -o hello
[tom@devbox hello_world_project]$ ./hello

上述命令将产生以下结果:

Hello, Modern Git!

验证代码后,他在本地 初始化(initializes) 一个 Git 仓库,添加 并 提交 他的文件:

[tom@devbox hello_world_project]$ git init -b main
Initialized empty Git repository in /home/tom/hello_world_project/.git/
[tom@devbox hello_world_project]$ git status -s
?? hello.c
[tom@devbox hello_world_project]$ git add hello.c
[tom@devbox hello_world_project]$ git status -s
A hello.c
[tom@devbox hello_world_project]$ git commit -m "Initial commit with hello.c"

接下来,他将 GitHub 仓库 的 URL(在 GitHub 上创建新 仓库 时提供,例如 https://github.com/yourusername/hello_world_project.git)添加为名为 origin 的 远程,并 推送 他的 main 分支:

[tom@devbox hello_world_project]$ git remote add origin https://github.com/yourusername/hello_world_project.git
[tom@devbox hello_world_project]$ git push -u origin main

认证:通过 HTTPS 向 GitHub 推送 时,Git 会提示输入凭据。此时必须使用 个人访问令牌(Personal Access Token,PAT),而不是您的密码。您可以从 GitHub 账户的开发者设置中生成 PAT。对于 SSH URL(例如 git@github.com:yourusername/hello_world_project.git),您需要使用 SSH 密钥。更多详细信息,请参阅 GitHub 关于 PATs 的文档。

Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Writing objects: 100% (3/3), 250 bytes | 250.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
To https://github.com/yourusername/hello_world_project.git
* [new branch] main -> main
Branch 'main' set up to track remote branch 'main' from 'origin'.

Tom 现在可以使用 git push 将任何后续变更 推送 到这个 GitHub 仓库。

Tom 成功地将他的项目 推送 到了 GitHub。现在,另一位开发者 Jerry 可以获取此项目的副本。

Jerry 创建一个目录,然后使用 GitHub 仓库 的 HTTPS URL 克隆 它:

[jerry@devbox ~]$ mkdir jerry_projects
[jerry@devbox ~]$ cd jerry_projects/
[jerry@devbox jerry_projects]$ git clone https://github.com/yourusername/hello_world_project.git

上述命令产生如下输出:

Cloning into 'hello_world_project'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), 250 bytes | 125.00 KiB/s, done.

他验证目录内容:

[jerry@devbox jerry_projects]$ ls
hello_world_project
[jerry@devbox hello_world_project]$ cd hello_world_project/
[jerry@devbox hello_world_project]$ ls
hello.c

Jerry 现在有了本地副本,可以开始贡献了。为了获取 Tom 的未来更新,Jerry 需要在他 hello_world_project 目录中使用 git pull 命令。