【问题标题】:How to delete old git branches before 1 year?如何在 1 年前删除旧的 git 分支?
【发布时间】:2021-12-22 02:52:26
【问题描述】:

我想在 git 分支之前列出所有 1 年,然后要求用户输入 YES 以删除所有列出的分支。

#!/bin/bash
if [[ "$data_folder" == "test" ]]; then

        current_timestamp=$(date +%s)
        twelve_months_ago=$(( $current_timestamp - 12*30*24*60*60 ))

        for x in `git branch -r | sed /\*/d`; do

                branch_timestamp=$(git show -s --format=%at $x)

                if [[ "$branch_timestamp" -lt "$twelve_months_ago" ]]; then
                        branch_for_removal+=("${x/origin\//}")
                fi
        done

if [[ "$USERCHOICE" == "YES" ]]; then
        git push origin --delete ${branch_for_removal[*]}
        echo "Finish!"
else
        echo "Exit"
fi

在 git 分支之前列出和删除所有 1 年的逻辑是否正确!

【问题讨论】:

  • 将您的文字发送至shellcheck.net,并在您担心下一部分之前解决明显的问题。
  • 在使用 shellcheck.net 之前不要忘记添加 shebang
  • 我相信 git show 只识别 blob、树、标签和提交,而不是分支:git-scm.com/docs/git-show。对于列出分支,您可能应该使用git branch --list
  • @JonathonS。 :git show 适用于分支名称。实际上:git 中的分支只是指向提交的指针。参见例如this section of the git book

标签: bash git git-bash


【解决方案1】:

整体逻辑看起来没问题(脚本中可能存在一些问题,例如您粘贴的代码中缺少关闭初始if [[ "$data_folder" == "test" ]]; thenfi)。

但是,有一些方法可以使用git 命令一次性列出您想要的数据:

  • 出于脚本目的,请使用git for-each-ref 而不是git branch

    # to list only refs coming from remotes/origin :
    git for-each-ref refs/remotes/origin
    
    # to have names 'origin/xxx` you are used to :
    git for-each-ref --format="%(refname:short)" refs/remotes/origin
    
    # to have the ref name without the leading 'origin/':
    git for-each-ref --format="%(refname:lstrip=3)" refs/remotes/origin
    
    # to have the timestamp of the latest commit followed by the refname :
    git for-each-ref --format="%(authordate:unix) %(refname:lstrip=3)" refs/remotes/origin
    

    查看git help for-each-ref了解更多详情

  • 您可以要求date 为您计算“1 年前”:date -d '1 year ago' +%s,
    并使用例如awk 一次性过滤您的输出:

    d1year=$(date -d '1 year ago' +%s)
    git for-each-ref --format="..." refs/remotes/origin |\
        awk '{ if ($1 < '$d1year') print $2 }'
    

另请注意:您可能需要检查committerdate 而不是authordate

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 2013-07-02
    • 2013-05-23
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    相关资源
    最近更新 更多