Skip to content

Git 使用指南

Git 是一个分布式版本控制系统,用于追踪代码变更和协作开发。

基础配置

bash
# 设置用户名和邮箱
git config --global user.name "Your Name"
git config --global user.email "your@email.com"

# 查看配置
git config --list

基础操作

初始化仓库

bash
# 初始化新仓库
git init

# 克隆远程仓库
git clone https://github.com/user/repo.git

暂存和提交

bash
# 查看状态
git status

# 添加文件到暂存区
git add filename.txt
git add .  # 添加所有文件

# 提交更改
git commit -m "Commit message"

# 添加并提交(快捷方式)
git commit -am "Commit message"

查看历史

bash
# 查看提交历史
git log

# 简洁显示
git log --oneline

# 显示文件改动
git diff

分支操作

bash
# 创建新分支
git branch feature-branch

# 切换分支
git checkout feature-branch
git switch feature-branch  # Git 2.23+

# 创建并切换
git checkout -b new-branch
git switch -c new-branch

# 列出分支
git branch

# 删除分支
git branch -d branch-name

远程操作

bash
# 添加远程仓库
git remote add origin https://github.com/user/repo.git

# 查看远程仓库
git remote -v

# 拉取代码
git pull origin main

# 推送代码
git push origin main

# 推送到默认分支
git push -u origin main

撤销操作

bash
# 撤销工作区修改
git checkout -- file.txt
git restore file.txt  # Git 2.23+

# 取消暂存
git reset HEAD file.txt

# 撤销提交(保留修改)
git reset --soft HEAD~1

# 撤销提交(不保留修改)
git reset --hard HEAD~1

实用技巧

储藏工作区

bash
# 储藏当前工作
git stash

# 查看储藏列表
git stash list

# 恢复储藏
git stash pop

标签管理

bash
# 创建标签
git tag v1.0.0

# 推送标签
git push origin v1.0.0

相关资源