Git 和 GitHub 完全使用指南

什么是 Git? Git 是一个分布式版本控制系统,用于跟踪文件的变化历史。它允许多个开发者协作开发项目,同时保持代码的完整性和可追溯性。 什么是 GitHub? GitHub 是一个基于 Git 的代码托管平台,提供了在线仓库、协作工具、CI/CD 等功能。它是全球最大的开源项目托管平台。 Git 基础概念 仓库(Repository) 存储项目代码和历史记录的地方。分为本地仓库和远程仓库。 分支(Branch) 独立的开发线。主分支通常是 main 或 master,可以创建其他分支进行特性开发。 提交(Commit) 保存一次代码变化的快照,包含作者、时间和变化说明。 推送(Push) 将本地提交上传到远程仓库。 拉取(Pull) 从远程仓库下载最新代码到本地。 Git 安装和配置 安装 Git Windows: # 使用 Chocolatey choco install git # 或从官网下载安装 # https://git-scm.com/ macOS: # 使用 Homebrew brew install git Linux: # Ubuntu/Debian sudo apt-get install git # CentOS/RHEL sudo yum install git 配置用户信息 # 设置用户名 git config --global user.name "Your Name" # 设置邮箱 git config --global user.email "your.email@example.com" # 查看配置 git config --list 常用 Git 命令 初始化和克隆 # 初始化本地仓库 git init # 克隆远程仓库 git clone https://github.com/username/repository.git 查看状态和历史 # 查看工作区状态 git status # 查看提交历史 git log # 查看简洁的提交历史 git log --oneline # 查看具体改动 git diff 添加和提交 # 添加文件到暂存区 git add filename # 添加所有改动 git add . # 提交改动 git commit -m "commit message" # 一步提交(仅限已跟踪的文件) git commit -am "commit message" 分支操作 # 查看本地分支 git branch # 查看所有分支 git branch -a # 创建新分支 git branch branch-name # 切换分支 git checkout branch-name # 创建并切换分支 git checkout -b branch-name # 删除分支 git branch -d branch-name # 合并分支 git merge branch-name 推送和拉取 # 推送到远程仓库 git push origin branch-name # 拉取远程更新 git pull origin branch-name # 获取远程更新(不合并) git fetch origin 撤销操作 # 撤销工作区改动 git checkout -- filename # 撤销暂存区改动 git reset HEAD filename # 撤销最后一次提交 git reset --soft HEAD~1 # 强制撤销(谨慎使用) git reset --hard HEAD~1 GitHub 工作流程 1. 创建仓库 登录 GitHub 点击 “New repository” 填写仓库名称和描述 选择公开或私有 初始化 README 文件(可选) 2. 克隆到本地 git clone https://github.com/username/repository.git cd repository 3. 创建特性分支 git checkout -b feature/new-feature 4. 进行开发 编辑文件,进行开发工作。 ...

2025-12-12 · 498 字 · MagicBude