0

I am trying to create a git pre-commit hook. If the current branch is already merged with the integration branch, I don't want to allow new commits to that branch. I have this:

#!/usr/bin/env bash

git fetch origin dev
current_branch=`git rev-parse --abbrev-ref HEAD`
branches="$(git branch --merged dev | tr '@squashed' '')"

say I have these two branches:

me/feature/x
me/feature/x@squashed

What I want to do is replace '@squashed', so I get this:

me/feature/x
me/feature/x

then if the current branch starts with either of those names, then exit with code 1.

The problem is:

  1. I can't figure out how to use tr/sed to only replace '@squashed' if the branch name ends with that string.

  2. I can't figure out how to loop over the elements and exit with non-zero if the current branch starts with one of the branch names in the list.

  • would it make more sense to assign the output of git branch to an array than a scalar? Bash also has some amount of variable expansion capabilities, where you can replace text in variables. – Jeff Schaller Sep 11 '18 at 10:45
2
  1. tr replaces single characters, not strings. As you surmise you can use sed to delete a string at the end of a line:

    git branch --merged dev | sed 's/@squashed$//'
    
  2. Instead of looping, use grep to determine whether a list of strings, one per line, contains a line starting with a reference string:

    git branch --merged dev | sed 's/@squashed$//' | grep -q "^..$current_branch"
    

Better yet, since you’re using git, ask it to filter for you:

git branch --list "${current_branch}*" --merged dev

will list any branch merged with dev whose name starts with the current branch. (Since you’re filtering by matching the start of branch names, you don’t need to drop the “@squashed” part, unless I’m missing something.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.