Git 详细教程

1. Git 简介

Git 是一个分布式版本控制系统,由 Linus Torvalds 为 Linux 内核开发而创建。它可以帮助开发者:

  • 跟踪代码变更
  • 协作开发
  • 回退到任意版本
  • 创建分支进行实验性开发

2. 安装 Git

Windows

  1. 下载 Git for Windows: https://gitforwindows.org/
  2. 运行安装程序,按照提示完成安装
  3. 安装完成后,可以在命令行中使用 git 命令

macOS

  1. 使用 Homebrew: brew install git
  2. 或从官网下载: https://git-scm.com/download/mac

Linux (Ubuntu/Debian)

sudo apt-get update
sudo apt-get install git

3. 配置 Git

安装后首先需要配置用户信息:

git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

查看配置:

git config --list

4. Git 基础操作

初始化仓库

git init

克隆现有仓库

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

检查状态

git status

添加文件到暂存区

git add filename       # 添加特定文件
git add .              # 添加所有更改
git add *.js           # 添加所有.js文件

提交更改

git commit -m "提交信息"

查看提交历史

git log
git log --oneline      # 简洁显示
git log --graph        # 图形化显示分支

5. 分支管理

查看分支

git branch

创建分支

git branch branch_name

切换分支

git checkout branch_name
# 或
git switch branch_name

创建并切换分支

git checkout -b branch_name
# 或
git switch -c branch_name

合并分支

git checkout main
git merge branch_name

删除分支

git branch -d branch_name      # 安全删除
git branch -D branch_name      # 强制删除

6. 远程仓库

添加远程仓库

git remote add origin https://github.com/username/repository.git

查看远程仓库

git remote -v

推送更改

git push -u origin main      # 第一次推送
git push                     # 之后推送

拉取更改

git pull origin main

获取远程更新但不合并

git fetch

7. 撤销操作

撤销工作区修改

git checkout -- filename

撤销暂存区修改

git reset HEAD filename

修改最后一次提交

git commit --amend

回退到特定提交

git reset --hard commit_id      # 彻底回退
git reset --soft commit_id      # 保留更改

8. 标签管理

创建标签

git tag v1.0.0
git tag -a v1.0.0 -m "版本1.0.0"  # 带注释的标签

查看标签

git tag

推送标签

git push origin v1.0.0
git push origin --tags          # 推送所有标签

删除标签

git tag -d v1.0.0
git push origin :refs/tags/v1.0.0  # 删除远程标签

9. Git 工作流

基本工作流程

  1. git pull 获取最新代码
  2. 进行修改
  3. git add 添加更改
  4. git commit 提交更改
  5. git push 推送更改

功能分支工作流

  1. main 分支创建功能分支
  2. 在功能分支上开发
  3. 完成后合并到 main 分支
  4. 删除功能分支

10. 高级主题

储藏更改

git stash              # 储藏当前更改
git stash list         # 查看储藏列表
git stash apply        # 应用最近的储藏
git stash pop          # 应用并删除储藏

变基 (Rebase)

git checkout feature
git rebase main

子模块

git submodule add https://github.com/username/repo.git
git submodule update --init --recursive

Git 钩子

.git/hooks/ 目录下可以添加各种钩子脚本

11. 常见问题解决

解决合并冲突

  1. 打开冲突文件
  2. 手动解决冲突 (删除 <<<<<<<, =======, >>>>>>> 标记)
  3. git add 标记为已解决
  4. git commit 完成合并

恢复被删除的分支

git reflog
git checkout -b branch_name commit_id

清理 Git 仓库

git gc

12. Git 图形化工具

  • GitKraken
  • Sourcetree
  • GitHub Desktop
  • Git GUI (内置)

13. 学习资源

results matching ""

    No results matching ""