Git脚本优化需求:仅在Pull后生成新的Repo归档文件
解决Git批量更新脚本中无效归档生成的问题
我写了一个bash脚本用于批量更新Git仓库并为每个仓库生成.bz2归档文件,逻辑是通过git fetch判断是否需要执行git pull,拉取完成后备份旧归档并创建新归档。但目前脚本存在问题:即使没有执行git pull,仍会生成新归档,需要优化成仅在仓库有更新(执行了git pull)时才生成归档。
原脚本的前2个仓库处理片段如下:
#!/bin/bash # update-sources.sh script SRCDIR=/home/darkside/Downloads/slack64-xfce4-source/xfce-master-build LOG=$PKGNAM-updated.log PKGNAM=exo-master # git clone https://gitlab.xfce.org/xfce/exo.gi cd $SRCDIR/exo/exo-master fetch=$(git fetch) if [[ -z "$fetch" ]] then echo "$PKGNAM-Local Repo up to date, no git pull needed" else git pull || echo "git pull required" || true | 2>&1 | tee $PKGNAM-$LOG fi cont=$(true) if [[ -z "$cont" ]] then cd .. mv *-master.tar.bz2 old-src-pkgs tar -cjf exo-master.tar.bz2 exo-master cd .. fi PKGNAM=garcon-master # git clone https://gitlab.xfce.org/xfce/garcon.git cd $SRCDIR/garcon/garcon-master fetch=$(git fetch) if [[ -z "$fetch" ]] then echo "$PKGNAM-Local Repo up to date, no git pull needed" else git pull || echo "git pull required" || true | 2>&1 | tee $PKGNAM-$LOG fi cont=$(true) if [[ -z "$cont" ]] then cd .. mv *-master.tar.bz2 old-src-pkgs tar -cjf garcon-master.tar.bz2 garcon-master cd .. fi
问题根源
原脚本中cont=$(true)这一行完全无效,true命令没有任何输出,导致[[ -z "$cont" ]]永远为真,所以不管仓库是否有更新,都会执行归档步骤。
优化后的脚本
我们需要添加一个更新标志变量,只有当仓库确实有更新(执行了git pull)时,才触发归档操作:
#!/bin/bash # update-sources.sh script SRCDIR=/home/darkside/Downloads/slack64-xfce4-source/xfce-master-build # 处理单个仓库的函数,减少重复代码 process_repo() { local repo_name=$1 local repo_path=$2 local log_file="${repo_name}-updated.log" echo "Processing ${repo_name}..." cd "${repo_path}" || { echo "Failed to enter ${repo_path}"; return; } # 执行git fetch,捕获输出 fetch_output=$(git fetch) local need_update=0 if [[ -z "$fetch_output" ]]; then echo "${repo_name}: Local Repo up to date, no git pull needed" else echo "${repo_name}: Pulling latest changes..." git pull 2>&1 | tee "${log_file}" need_update=1 fi # 只有当有更新时才生成归档 if [[ $need_update -eq 1 ]]; then cd .. # 备份旧归档(如果存在) if [[ -f "${repo_name}.tar.bz2" ]]; then mv "${repo_name}.tar.bz2" old-src-pkgs/ fi tar -cjf "${repo_name}.tar.bz2" "${repo_name}" echo "${repo_name}: New archive generated" cd .. fi } # 逐个处理仓库 process_repo "exo-master" "${SRCDIR}/exo/exo-master" process_repo "garcon-master" "${SRCDIR}/garcon/garcon-master" # 继续添加其他23个仓库的调用...
关键改动说明
- 封装函数减少重复代码:把单个仓库的处理逻辑封装成
process_repo函数,避免25个仓库重复写相同代码,后续维护更方便。 - 添加更新标志
need_update:初始设为0,只有当git fetch有输出(即仓库有更新)并执行了git pull后,才将标志设为1。 - 归档逻辑依赖标志变量:只有
need_update为1时,才执行备份旧归档、生成新归档的操作。 - 完善错误处理:添加
cd命令的错误判断,避免路径不存在时脚本崩溃。 - 日志文件路径修正:原脚本中
LOG=$PKGNAM-updated.log在PKGNAM赋值前执行,会导致变量为空,现在在函数内生成正确的日志文件名。
内容的提问来源于stack exchange,提问作者urbanmusic
相关产品推荐
相关产品推荐

