Git 初学者指南:如何 Push & Pull 代码、跟踪更改并了解版本控制

发布: (2026年1月18日 GMT+8 15:38)
3 min read
原文: Dev.to

Source: Dev.to

Git 基础入门

Git 是一种版本控制工具,帮助开发者跟踪代码的更改并安全协作。Git 不会为同一个文件创建多个版本,而是记录 什么 发生了变化、何时 变化以及 做了更改。这使得团队协作更容易,也能从错误中快速恢复。

Git 在一个称为 仓库(repository)的项目文件夹中工作。你在本地电脑上进行操作,然后将更改同步到远程仓库(例如 GitHub)。

使用仓库

开始一个新项目

git init                # create a new empty repository
git remote add origin   # (optional) link to a remote

克隆已有项目

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

检查仓库状态

git status              # shows staged, unstaged, and untracked files

暂存更改

暂存特定文件

git add path/to/file

暂存所有更改

git add .

提交更改

保存检查点

git commit -m "Your descriptive commit message"

推送更改到远程

第一次推送(设置上游)

git push -u origin main

常规推送

git push

从远程拉取更改

获取最新更新

git pull               # fetches and merges remote changes

提示: 在开始工作前一定要先 pull,以避免冲突。

查看历史

提交日志

git log                # shows commit history

查看文件的更改内容

git diff               # shows unstaged changes
git diff HEAD~1 HEAD   # shows changes introduced by the last commit

常见陷阱

  • 工作前忘记 pull,导致合并冲突。
  • 编写不清晰的提交信息。
  • 提交了有错误的代码。
  • 害怕犯错(Git 设计初衷就是安全恢复)。

必记核心命令

  • git status – 查看当前仓库状态。
  • git add – 暂存更改。
  • git commit – 记录快照。
  • git push – 将提交发送到远程。
  • git pull – 获取并合并远程更改。

其他所有操作都建立在这些基础之上。祝编码愉快!

Back to Blog

相关文章

阅读更多 »