理解 Git 版本控制:跟踪更改、Commit、Push 与 Pull(初学者指南)
Source: Dev.to
什么是版本控制、Push 和 Pull
版本控制 (Git)
版本控制是一种记录文件随时间变化的系统。
简单来说,它就像为你的项目提供了一个保存历史。使用 Git 时,你会创建称为 提交(commits) 的检查点。每个提交都会成为项目历史的一部分,这样你就可以看到哪些内容改变了、了解何时改变的,并在需要时回到早期版本。
常用 Git 命令
git status # Show changed files and their commit status
git add . # Stage all changed files for the next commit
git commit -m "..." # Create a commit with a message
git log # List all commits with author, date, and message
git show # Show the changes introduced by a specific commit
git restore # Revert a file to the last committed state
git checkout # View an older version without altering current work
git checkout main # Return to the latest version on the main branch
Push
Push 意味着将本地仓库中已保存的提交发送到远程仓库(例如 GitHub)。执行 push 时:
- 你的工作会上传到 GitHub。
- 它会在网上得到备份。
- 其他人可以共享或协作使用。
如果不进行 push,工作只会保留在你的电脑上。
常见的 push 工作流
# First push of a new repository
git push -u origin main # Use "master" instead of "main" if your default branch is master
# Check which branch you are on
git branch # or git status
# Rename the current branch to main (if needed)
git branch -M main
# Subsequent pushes
git push
注意: 在 push 之前,必须使用
git add和git commit将更改提交。
Pull
Pull 意味着从远程仓库(例如 GitHub)下载最新的提交到本地仓库。
这在以下情况下很重要:
- 你在多台电脑上工作,需要在各处拥有相同的文件。
- 你与他人协作,需要获取他们的最新更改。
- 有人在 GitHub 上直接进行了更新,你需要在本地获取这些更新。
与 pull 相关的命令
git pull # Download and integrate changes from the remote
git fetch # Check for updates without merging them
git merge # Combine fetched changes with your local files
git fetch 只会更新本地对远程提交的认识;它 不会 修改你的工作文件。想在应用更改前先审查时使用它。
其他有用的选项(后面会介绍)包括 git pull --rebase、git restore 和 git reset --hard。
实践示例:在 GitHub 上跟踪更改并进行 Push/Pull(第 4 部分)
现在我们已经了解了版本控制、push 和 pull,系列的下一部分将演示一个简单的端到端示例,展示这些命令如何协同工作。敬请期待第 4 部分,届时我们还会探讨更多 Git 命令。