I have a git alias for force pushing current branch:

    fp = "!git push -f origin \"$(git rev-parse --abbrev-ref HEAD)\""

Which basically maps fp to a command that does a force push to the current branch, which it extracts from git rev-parse.

Problem: sometimes I am not paying attention and I do git fp when I'm on master branch. This could obviously be really bad if there are no branch protection rules in place on the repository.

I want to prevent myself from making this future mistake. How can I update my alias command to do the same thing, except only do it if the branch name is something other than master?

  • does your host support branch security policies? Apr 24, 2023 at 19:46
  • @FrankThomas the problem is that I work in an organization with many repos, and make changes to many different repos. So far, most repos have a branch policy in place. And I actually accidentally did git fp on a few of these and got rejected. But I've also seen some repos without branch protection rules and luckily have not made this mistake (yet) Apr 24, 2023 at 23:34
  • 1
    consider why you have to do force pushes so regularly that you need an alias for it. somthing is very wrong with your workflow if it is actually required. Apr 25, 2023 at 16:02
  • @FrankThomas definitely just me being lazy, I can't even recall what limitation I ran into that forced me into it, thanks for calling that out May 5, 2023 at 22:50

1 Answer 1


You can use a condition just like in regular bash:

    fp = "!branch=$(git branch --show-current); [[ -z $branch || $branch = 'master' ]] && echo 'Command cannot be used on master branch or when not on branch.' || git push -f origin \"$(git rev-parse --abbrev-ref HEAD)\""

This first saves the branch name from git branch --show-current to a var, then compares it to master and echoes a warning if it's a match, otherwise executes your command.

Maybe a bit more reliable version in some cases when outside of a branch:

    fp = "!branch=$(git rev-parse --abbrev-ref HEAD); [ \"$branch\" = 'master' ] && echo 'Command cannot be used on master branch' || git push -f origin \"$branch\""

But you probably don't want to attempt to push then either.

Note that these commands may not work and need more convoluted formatting (e.g. with !f() { } syntax) in older git versions, this is assuming the latest one as of now (2.40).


You must log in to answer this question.

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