📋 核心要点
  • 清理远程已删除的本地分支:git fetch --prune + 过滤 : gone(中文环境 : 丢失)再批量删除
  • 回退提交三档:--hard(丢弃工作区)、--soft(保留改动并标记待提交)、--mixed(保留改动但不标记)
  • 克隆时用指定 RSA 密钥:先 ssh-add 把私钥加入 ssh-agent,再执行 clone
  • ssh-agent 脚本必须用 . script.shsource script.sh 启动,才能在当前 shell 生效

删除远程不存在的本地分支

fetch --prune 同步远端分支状态,再过滤出本地已跟踪但远端已删除的分支批量清理。

Bash
# Linux(中文环境)
git fetch --prune
git branch -vv | grep ': 丢失' | awk '{print $1}' | xargs git branch -D

# Linux(英文环境)
git fetch --prune
git branch -vv | grep ': gone' | awk '{print $1}' | xargs git branch -D
PowerShell
# Windows PowerShell(中文环境)
git fetch --prune
git branch -vv | Select-String ': 丢失' | ForEach-Object { $_.ToString().Split(" ")[2] } | ForEach-Object { git branch -D $_ }

# Windows PowerShell(英文环境)
git fetch --prune
git branch -vv | Select-String ': gone' | ForEach-Object { $_.ToString().Split(" ")[2] } | ForEach-Object { git branch -D $_ }

回退最近的几次提交

将 HEAD 指针移动到上一次提交:

Bash
git reset --hard HEAD~1
  • --hard:工作目录也回退到该提交状态,丢弃当前工作区的所有更改
  • --soft:保留更改并标记为待提交
  • --mixed:保留更改但不标记为待提交(默认行为)
Bash
git reset --soft HEAD~1
git reset --mixed HEAD~1

克隆仓库时使用自己的 RSA 密钥

当不同仓库需要不同私钥时,用 ssh-agent 显式添加指定私钥再克隆:

Bash
#!/usr/bin/env bash

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)

killall ssh-agent

# 启动代理
eval "$(ssh-agent -s)"

# 添加 RSA 私钥
ssh-add "${script_dir}/id_rsa"

# 查看是否添加成功
ssh-add -l
⚠️ 注意事项
  1. 启动时必须用 . ssh_agent.shsource ssh_agent.sh,才能让环境变量在当前 shell 生效
  2. 可用 echo $SSH_AGENT_PIDecho $SSH_AUTH_SOCK 检查是否启动成功