Home > Enterprise >  Zsh function to check if git branches exist and then delete those git branches
Zsh function to check if git branches exist and then delete those git branches

Time:06-28

I'm trying to write a simple zsh function to delete all git branches with a specific pattern. The function contains a simple conditional that checks if any branches need to be deleted. If so, it deletes them. If not, it echos that there are no branches to be deleted.

Here is what I have so far:

deletedependabotbranches () {
  dependabot_branches=$(git branch | grep '^\*\?\s*dependabot/')
  if dependabot_branches ; then
    echo "Deleting dependabot branches..."
    git branch -D dependabot_branches
  else
    echo "No dependabot PR's found"
  fi
}

But I'm getting the following error:

command not found: dependabot_branches

How can I write this simple function?

CodePudding user response:

put the assignment directly into the if like this:

if dependabot_branches=$(git branch | grep '^\*\?\s*dependabot/')
then this
else that
fi

but your script's got worse problems, git branch isn't really intended for scripting use and you're going to wind up executing a wildcard branch delete if you've got one of the dependabot branches checked out.

git for-each-ref --format='delete %(refname)' refs/heads/dependabot\* \
| git update-ref --stdin
  • Related