1

I want to list all 1 year before git branches and then ask user to type YES tto delete all the listed branches.

#!/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

Is this logic correct to list and delete all 1 year before git branches !!

Ansh
  • 55
  • 8
rowoc
  • 239
  • 2
  • 12
  • 2
    Feed your text to `shellcheck.net` and fix the obvious issues before you worry about the next part. – torek Nov 09 '21 at 11:45
  • 2
    Don't forget to add a shebang before you use shellcheck.net – Jetchisel Nov 09 '21 at 11:47
  • 1
    I believe `git show` identifies blobs, trees, tags and commits only, not branches: https://git-scm.com/docs/git-show. For listing branches you should probably use `git branch --list`. – Jonathon S. Nov 09 '21 at 12:48
  • 1
    @JonathonS. : `git show` works fine with branch names. Actually : branches in git are just pointers to commits. See for example [this section of the git book](https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell) – LeGEC Nov 09 '21 at 13:46
  • https://stackoverflow.com/q/10325599/7976758 – phd Nov 11 '21 at 11:49

1 Answers1

2

The overall logic looks ok (there may be some issue in the script, for example the fi which closes the initial if [[ "$data_folder" == "test" ]]; then is missing from the code you pasted).

There are however ways to use git commands to list the data you want in one go :

  • for scripting purposes, use git for-each-ref rather than 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
    

    see git help for-each-ref for more details

  • you can ask date to compute the "1 year ago" for you : date -d '1 year ago' +%s,
    and use e.g awk to filter your output in one go :

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

Also note : you may want to check the committerdate rather than the authordate

LeGEC
  • 46,477
  • 5
  • 57
  • 104