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:


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


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, 2018 at 10:45

1 Answer 1

  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.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .