[效率提升]使用shell脚本完成一些git操作
根据分支名自动Add和Commit并Push到远程开发分支
例如开发分支名为: feature-xxx功能
Commit信息为:xxx功能
#!/bin/bash# 获取当前分支名称
current_branch=$(git rev-parse --abbrev-ref HEAD)echo "current branch: ${current_branch}"# 去掉“feature-”后剩下的内容
commit_message=${current_branch#feature-}
echo "commit message: $commit_message"# 提交代码并推送到远程仓库
git add .
git commit -m "$commit_message"
git push origin "$current_branch"
自动合并变化到develop分支里
同上,只是增加了将开发分支内容合并到develop分支的操作
# 判断当前分支
current_branch=$(git branch --show-current)# 判断目标分支是否存在
target_branch=$(git branch --list develop)echo "current branch: ${current_branch}"
echo "target branch: ${target_branch}"# 去掉“feature-”后剩下的内容
commit_message=${current_branch#feature-}
echo "commit message: $commit_message"git add .
git commit -m "$commit_message"
git push origin "$current_branch"# 判断develop分支是否存在
if [ -z "$target_branch" ]; thenecho "develop本地分支不存在"git checkout -b develop origin/develop
elsegit checkout developgit pull origin develop:develop
fi# 合并分支
git merge --no-edit "$current_branch"# 判断拉取更新后是否有冲突
conflict_num=$(git status --porcelain | grep '^UU' | wc -l)
echo "Conflict number: ${conflict_num}"
if [ "$conflict_num" -gt 0 ]; then# 把当前文件区还原到develop最新的一次commitgit reset --hard HEADecho -e "\033[41m There are conflicts, please solve them! \033[0m"
elseecho -e "\033[42mMerge successfully!\033[0m"# 输入y确认push,此时可在sourcetree等工具查看合并状况,确认后再输入y执行pushread -p "push it immediately?(y/n):" inputinput=$(echo "$input" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')if [[ $input == "y" ]]; then# push上去 最后还是自己来操作比较稳妥git push origin developecho -e "\033[42mPush OK!\033[0m"# 切换回原来的分支继续搬砖git checkout "$current_branch"elseecho -e "\033[41mCancel!\033[0m"echo -e "\033[41mStay in develop!\033[0m"exit 1fi
fi
删除无用分支
例如每次上线都会产生一个当前日期的预发分支,时间久了就会在本地堆积很多无用分支
#!/bin/bash# 列出所有符合条件的分支
git branch -r --list "origin/frontend-en-2023-*" | while read branch; doecho "$branch"
done# 确认是否删除分支
read -p "以上分支将会被删除,是否继续(Y/N)?" choice
case "$choice" iny|Y )# 删除所有符合条件的分支git branch -r --list "origin/frontend-en-2023-*" | while read branch; doecho "当前删除的本地远程分支:${branch#origin/}"# 删除本地远程分支git branch -d -r "${branch}"# 删除远程分支# git push origin --delete "${branch#origin/}"doneecho "分支已删除";;* )echo "取消删除";;
esac
查看近一个月未改动的分支
#!/bin/bash# 检测并获取近一个月都没有变动的 Git 分支列表
function get_stale_branches {# 获取一个月前的时间戳one_month_ago=$(date -d "1 month ago" +%s)# 获取所有分支列表branches=$(git for-each-ref --format='%(refname:short) %(committerdate:unix)' refs/)# 过滤出近一个月都没有变动的分支stale_branches=$(awk -v one_month_ago="$one_month_ago" '$2 < one_month_ago {print $1}' <<< "$branches")# 返回目标分支列表echo "$stale_branches"
}# 调用函数并将结果存储在变量中
stale_branches=$(get_stale_branches)# 打印目标分支列表
printf "Stale branches:\n%s\n" "$stale_branches"