Git Bash(拉取和推送代码,跟踪更改和版本控制)

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

Source: Dev.to

前置条件

  • 一个 GitHub 账户
  • 已安装并配置好可连接 GitHub 的 Git Bash
  • 一个 IDE(例如 Visual Studio Code)

介绍

Git Bash 是 Windows 下的命令行应用程序,提供类 Unix 的终端环境,用于操作 Git 和 GitHub。它让你能够运行 pushpullcommitclone 等命令来管理托管在 GitHub 上的代码仓库。

Git 是一种版本控制系统,用于追踪源代码的更改。它记录 什么 被改动、何时 改动、 做了改动,并在需要时允许你恢复到之前的版本。这有助于安全协作、防止意外丢失工作,并使调试更容易。

创建本地仓库

# Initialize a new Git repository in the current folder
git init

# Add all files to the staging area
git add .

# Or add a specific file
git add filename.ext

# Check the repository status
git status

进行首次提交

git commit -m "Add initial project files"
# Set the default branch name to 'main'
git branch -M main

连接到 GitHub 上的远程仓库

# Replace <URL> with the URL of your GitHub repository
git remote add origin <URL>

推送代码到 GitHub

git push -u origin main

你可以使用以下命令查看提交历史:

git log

git log 会显示提交哈希、作者、日期以及提交信息。

从 GitHub 拉取代码

方法 1 – 克隆(首次)

# Replace <URL> with the URL of the remote repository
git clone <URL>

此命令会创建一个与仓库同名的文件夹,下载所有文件,并将 origin 设置为该 GitHub 仓库。

方法 2 – 拉取(后续更新)

# Verify you are on the correct branch
git branch

# Pull all updates and merge them into the current branch
git pull

# Or pull a specific branch (e.g., development)
git pull origin development

追踪更改

git log

git log 会显示提交的时间、提交者以及对应的提交信息。

恢复有问题的更改

如果最近的提交引入了 bug,你可以将其恢复:

# Replace <commit-hash> with the commit hash you want to revert
git revert <commit-hash>

恢复后,推送更新后的历史以保持远程仓库同步:

git push -u origin main

小结

现在你已经了解如何:

  • 初始化本地 Git 仓库
  • 提交更改并设置默认分支
  • 连接并推送代码到远程 GitHub 仓库
  • 克隆和拉取 GitHub 的更新
  • 使用 git log 追踪提交历史
  • 恢复不需要的更改

这些基础知识能够帮助你在任何软件项目中实现高效的协作与版本控制。

Back to Blog

相关文章

阅读更多 »

Git Bash 与 GitHub 初学者入门

什么是 Git?Git 是一个免费、开源的版本控制系统,用于随时间跟踪代码或任何文件的更改。它让开发者能够:- 在项目上工作……