想学习 Git 和 GitHub 吗?版本控制一步步指南
I’m happy to help translate the article, but I need the full text you’d like translated. Could you please paste the content (or the portion you want translated) here? I’ll keep the source line, formatting, markdown, and any code blocks exactly as they are while translating the rest into Simplified Chinese.
介绍
如果你和许多初学者一样,可能已经听说过“推送到 main”或“合并分支”等术语,并且好奇它们的含义。本指南将带你了解 Git 和 GitHub 的基础知识,展示如何安装、配置以及有效地使用它们来管理代码。
什么是 Git?
Git 是一个版本控制系统——为你的代码提供智能历史记录的工具。每当你进行更改时,Git 会记录这些更改,使你能够:
- 跟踪修改 – 查看哪些内容被更改、何时更改以及由谁更改。
- 回滚 – 如果出现问题,可以返回到之前的状态。
GitHub 是什么?
GitHub 是一个基于网页的 Git 仓库托管服务(可以把它看作是代码的云端)。它可以让你:
- 存储 – 为你的项目保留备份。
- 分享 – 让其他人可以访问你的代码。
- 协作 – 提供一个中心枢纽,团队合作时不会相互覆盖工作。
- 展示 – 构建你的项目作品集。
安装 Git Bash(Windows)
-
下载 Git Bash,来自官方网站。
-
运行安装程序 并按照屏幕指示进行。默认选项适用于大多数用户。
- 选择默认编辑器:保持默认(Vim)或选择您喜欢的其他编辑器(VS Code、Notepad++ 等)。
- 调整初始分支的名称:选择 “让 Git 决定”(它现在默认是
main)。
-
验证安装:打开 Git Bash 并运行
git --version您应该会看到 Git 的版本号。
配置 Git
在使用 Git 之前,设置你的身份信息:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
验证设置:
git config --global --list
设置 GitHub 账户和 SSH 密钥
-
创建 GitHub 账户。
-
生成 SSH 密钥(这样每次就不会提示输入密码):
ssh-keygen -t ed25519 -C "your@email.com"按 Enter 键通过提示,接受默认设置。
-
启动 SSH 代理:
eval "$(ssh-agent -s)" -
将 SSH 密钥添加到代理:
ssh-add ~/.ssh/id_ed25519 -
复制公钥:
cat ~/.ssh/id_ed25519.pub复制显示的字符串。
-
将密钥添加到 GitHub:
- 前往 Settings → SSH and GPG keys → New SSH key。
- 粘贴复制的密钥并保存。
初始化本地仓库
假设你有一个名为 my-cool-app 的文件夹。
cd path/to/my-cool-app
git init
创建一个简单的文件,例如 readme.txt,内容为 “Hello world”。
添加并提交
git add .
git commit -m "My first save point"
在 GitHub 上创建远程仓库
- 在 GitHub 上,点击 New repository 并为其命名。
- 复制类似
git@github.com:yourname/your-repo.git的 SSH URL。
链接远程仓库
git remote add origin git@github.com:yourname/your-repo.git
推送到 GitHub
git push -u origin main
刷新 GitHub 页面——你应该能看到在线的代码。
拉取更改
如果你在另一台电脑上工作,或有协作者更新了仓库,请将这些更改同步到本地副本:
git pull origin main
“三大”命令
| Action | Command | Purpose |
|---|---|---|
| Add | git add <file> | 将想要记录的更改加入暂存区 |
| Commit | git commit -m "message" | 保存已暂存更改的快照 |
| Push | git push | 将提交发送到远程仓库 |
如果一开始忘记了命令也不用担心——搜索它们是学习过程的一部分。坚持练习,很快就会变得自然。
祝编码愉快! 🥳