Skip to content

Instantly share code, notes, and snippets.

@jiacai2050
Created February 9, 2026 09:56
Show Gist options
  • Select an option

  • Save jiacai2050/0cd2cfa71e97df7e6dd619e7451ff58f to your computer and use it in GitHub Desktop.

Select an option

Save jiacai2050/0cd2cfa71e97df7e6dd619e7451ff58f to your computer and use it in GitHub Desktop.
基于当前的修改(staged/unstaged)生成 patch 文件
#!/usr/bin/env bash
set -Eeuo pipefail
# 获取当前分支和时间
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
INCLUDE_UNSTAGED=false
# 处理输入参数
while [[ "$#" -gt 0 ]]; do
case $1 in
-a|--all) INCLUDE_UNSTAGED=true ;;
*) echo "未知参数: $1"; exit 1 ;;
esac
shift
done
# 根据逻辑确定 diff 命令和文件名后缀
if [ "$INCLUDE_UNSTAGED" = true ]; then
# 包含所有改动 (Staged + Unstaged)
CMD="git diff HEAD"
TYPE="full"
else
# 仅包含已暂存的改动
CMD="git diff --cached"
TYPE="staged"
fi
FILENAME="/tmp/patch_${BRANCH_NAME}_${TYPE}_${TIMESTAMP}.patch"
# 检查是否有内容可以生成
if [ "$INCLUDE_UNSTAGED" = true ]; then
if git diff --quiet && git diff --cached --quiet; then
echo "❌ 错误: 没有任何改动(已暂存或未暂存)。"
exit 1
fi
else
if git diff --cached --quiet; then
echo "❌ 错误: 没有已暂存 (Staged) 的改动。"
echo "提示: 使用 -a 参数可以包含未暂存的改动。"
exit 1
fi
fi
# 执行生成
$CMD > "$FILENAME"
echo "✅ 补丁已生成 ($TYPE),使用方法: "
echo "git apply $FILENAME"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment