如何自动为Git仓库所有分支添加并推送.gitattributes文件?
批量为Git所有分支添加.gitattributes并推送
前置准备
- 先在仓库外的位置创建好预填充的
.gitattributes文件,比如~/git-lfs-attributes,内容根据你的LFS需求编写,示例:
# Git LFS配置 *.psd filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.mp4 filter=lfs diff=lfs merge=lfs -text
- 拉取所有远程分支到本地(如果本地还没有全部分支):
git fetch --all # 将远程分支转为本地跟踪分支 git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
- 确保本地仓库没有未提交的修改,避免切换分支失败。
批量处理脚本
创建一个bash脚本(比如add-attributes.sh),内容如下:
#!/bin/bash # 预准备的.gitattributes文件路径 ATTRIBUTES_FILE=~/git-lfs-attributes # 获取所有本地分支(排除HEAD和当前分支标记) branches=$(git branch | grep -v "HEAD" | sed 's/* //') # 遍历每个分支处理 for branch in $branches; do echo "=== 开始处理分支: $branch ===" # 切换到目标分支 git checkout "$branch" || { echo "切换分支失败,跳过"; continue; } # 复制预准备的文件到分支根目录 cp "$ATTRIBUTES_FILE" .gitattributes # 检查文件是否已存在且内容一致,避免重复提交 if git diff --quiet -- .gitattributes; then echo "该分支的.gitattributes已存在且内容一致,跳过提交" continue fi # 提交修改 git add .gitattributes git commit -m "Add Git LFS configuration via .gitattributes" # 推送到远程仓库 git push origin "$branch" echo "=== 分支 $branch 处理完成 ===" done # 切回原分支 git checkout -
运行脚本
- 给脚本添加执行权限:
chmod +x add-attributes.sh - 在仓库根目录运行脚本:
./add-attributes.sh
注意事项
- 先备份仓库:建议先克隆一个测试仓库,验证脚本正常后再在正式仓库运行。
- 脚本会覆盖分支中已存在的
.gitattributes文件,如果需要保留原有文件,可在脚本中添加判断逻辑,比如对比内容后选择合并或跳过。 - 如果部分分支推送失败(比如权限问题、远程分支已更新),脚本会跳过该分支,后续可单独处理这些分支。
- 添加完
.gitattributes后,若要将分支中已存在的大文件迁移到LFS,可在对应分支运行:git lfs migrate import --include="指定文件后缀",之后重新推送分支。
内容的提问来源于stack exchange,提问作者L Holden
相关产品推荐
相关产品推荐

