Reputation: 249
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 !!
Upvotes: 1
Views: 936
Reputation: 51840
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
Upvotes: 3