本文是 Git 日常使用的手册式整理:配置、认证、子模块、分支、撤销与恢复。命令按使用场景组织,方便查阅。

一、配置

1.1 配置优先级

仓库级配置 > 全局配置 > 系统级配置
git config --list                    # 查看全部配置
git config [--global] config_name    # 查看某个配置
git config [--global] --unset-all config_name   # 取消配置

1.2 账号配置

# 生成密钥(-C 指定邮箱注释)
ssh-keygen -t rsa -C "youxiang@163.com"

# 配置用户名和邮箱
git config user.email "you@example.com"
git config user.name "Your Name"

把公钥添加到 Git 平台的 SSH 公钥设置中即可免密拉取。

二、代理与超时

# HTTP 代理
git config http.proxy 'http://192.168.0.1:1080'
git config https.proxy 'http://192.168.0.1:1080'

# 单个仓库的 push/pull 超时
git config remote.origin.pushTimeout 60
git config remote.origin.pullTimeout 60

# 对所有仓库生效:设置 SSH 连接超时
export GIT_SSH_COMMAND='ssh -o ConnectTimeout=20'

三、拉取提交流程

推荐先本地提交,再用 rebase 方式拉取并合并:

git commit -m "..."

# 拉取远程更新并把自己的提交变基到最新
git pull --rebase

四、子模块管理

4.1 添加子模块

# --depth 1 只拉取最新提交,减少体积
git submodule add --depth 1 https://url.git

# 指定 tag:进入子模块目录
git fetch origin tag v2.x --depth 1
git checkout v2.x

4.2 拉取子模块

# 克隆时直接拉取
git clone --recursive

# 已克隆后拉取
git submodule update --init --recursive

4.3 删除子模块

# 1. 删除 .gitmodules 中相关条目
# 2. 删除 .git/modules/ 下相关目录
# 3. 删除子模块工作目录
# 4. 再次 submodule add 重新添加

五、分支管理

5.1 查看分支

git branch -r      # 远程分支
git branch         # 本地分支
git branch -a      # 所有分支
git branch -vv     # 本地分支与远程分支的对应关系

5.2 创建并推送分支

git branch new_branch_name
git push -u origin new_branch_name

5.3 切换分支

git checkout -b local_branch_name remote_url/branch_name

5.4 删除分支

git branch -D branch_name

六、fetch 与 pull 的区别

# fetch:只更新远程跟踪引用,本地工作区不变
git fetch origin
git merge origin/master   # 手动合并

# pull:fetch + merge 一步完成
git pull
  • fetch 安全,只更新本地对远程状态的认知。
  • pull 会直接合并到当前分支,可能产生冲突。

七、撤销提交

# 撤销最近一次提交,保留改动和暂存状态(soft 保留到 add 之后)
git reset --soft HEAD~

--soft 只移动 HEAD 指针,改动保留在暂存区,适合“提交信息写错”的场景。

八、切换版本与恢复文件

# 切换到指定提交(detached HEAD)
git checkout commit_hash_value

# 切换回分支
git checkout branch-name

# 恢复被修改或误删的文件
git status                # 查看当前改动路径
git checkout file_path    # 用仓库版本覆盖工作区文件

九、查看仓库信息

git remote -v

十、总结

  • 配置优先级:仓库 > 全局 > 系统。
  • 子模块用 --depth 1 减体积,删除要清理三处。
  • fetch 只更新远程状态,pull 会合并。
  • reset --soft 保留改动撤销提交,checkout 恢复单个文件。
  • 代理和超时配置可以按仓库或全局生效。

相关脚本

整理自 cyy-tag/bash-example 仓库: