Skip to content
Go back

Git 版本控制小记

Updated:
Edit page

Contents

Open Contents

Git 基础概念

Git的分布式特性:每个开发者都有完整的仓库副本
Git的三个重要区域:工作目录、暂存区和仓库

安装与配置

安装 Git

参阅 Git - Downloads

基础配置

在使用 Git 之前,首要任务是配置你的用户名(username)邮件地址(email address),之后使用 Git 的每一次提交都会使用这些信息

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

# 查看配置
git config --list

有时候克隆或者推送远程库时(GitHub)可能碰上请求超时的问题,需要配置或取消一下代理

# HTTP 代理
git config --global http.proxy <你的代理IP:端>
# HTTPS 代理
git config --global https.proxy <你的代理IP:端>

# 取消代理
git config --global --unset http.proxy
git config --global --unset https.proxy

# 针对当前终端会话临时取消
unset ALL_PROXY
unset HTTP_PROXY
unset HTTPS_PROX

基础操作

创建/克隆仓库

# 本地初始化新仓库
mkdir [git-repo-name] && cd [git-repo-name]
git init
# 等价于
git init [git-repo-name]

# 克隆现有仓库
git clone <repository_url>

文件状态管理

# 查看当前状态
git status
# 图形化显示全部分支的提交历史
git log --oneline --all --graph

# 添加文件到暂存区
git add <file>  # 添加单个文件
git add .       # 添加所有修改

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

# 从暂存区撤销
git restore --staged <file>

分支管理

# 查看分支
git branch       # 本地分支
git branch -a    # 所有分支(包括远程)

# 创建分支
git branch <branch_name>

# 切换(签出)分支
git checkout <branch_name>
# 或创建并切换:
git checkout -b <new_branch>

# 合并分支(需先切换到目标分支)
git merge <source_branch>

# 删除分支
git branch -d <branch_name>   # 安全删除(已合并)
git branch -D <branch_name>   # 强制删除(未合并)

远程操作

# 查看远程仓库
git remote -v

# 添加远程仓库
git remote add <remote_name> <repository_url>
# 从本地 Git 仓库删除远程仓库
git remote remove <name>
# 重命名远程仓库
git remote rename <old-name> <new-name>

# 推送分支到远程
git push <remote> <branch>
git push -u origin main      # -u设置默认上游分支

# 拉取远程更新(会合并)
git pull <remote> <branch>

# 获取远程更新(不自动合并)
git fetch <remote>
# 获取远程最新信息,并执行「修剪」操作,比如删除已经不存在的远程分支引用
git fetch -p

撤销与回退

git reset用于取消已经提交的变更、移动 HEAD 指针、重置暂存区和工作目录等操作,会直接修改/删除提交历史,通常适用于本地分支的修改撤销

# 撤销工作区修改(未add)
git restore <file>

# 撤销暂存区修改(已add)
git reset <file>

# 撤销提交(回退到指定commit)
git reset --soft <commit>   # 保留更改在暂存区
git reset --mixed <commit>  # 保留更改在工作区(默认)
git reset --hard <commit>   # 彻底丢弃更改

# 用例:撤销上一次提交,并保留更改在暂存区
git reset --soft HEAD~1
# 如果想删除远程仓库的提交记录,需要(慎重!):
git push --force

# 修改最后一次提交
git commit --amend -m "new message"

git revert 用于撤销某次提交的更改,但不会删除该提交历史,而是创建一个新的”反向提交”来抵消原提交的更改,通常适用于公共分支的修改撤销

git revert <commit>

# 同时撤销多个提交
git revert <commit1> <commit2> ...

git revert HEAD~1

Edit page
Share this post on:

Previous Post
AI Agent 基本设计模式
Next Post
Git 提交中两个重要的配置文件:.gitignore与.gitattributes