Shell script to check if specified Git branch exists?

This question already has an answer here:

  • Is there a better way to find out if a local git branch exists?

    11 answers

  • How to listen to webhooks from bash script?
  • Git Status Across Multiple Repositories on a Mac
  • state of git is confused by switching branches in a script
  • Import files directly to SVN repo without checking out first
  • RVM “ERROR: Unable to checkout branch .” single-user
  • Count number of lines in a git repository
  • Are conflicts unavoidable when cherry picking a commit?
  • Can I run git locally on my box and still play nicely with the company SVN repo?
  • git branching - how to make current master a branch and then revert master back to previous version?
  • Git Moving Files into Folders
  • replay git commits on repo with different root
  • Don't work git in Android Studio
  • 2 Solutions collect form web for “Shell script to check if specified Git branch exists?”

    You could always use word boundaries around the name like \< and \>, but instead let Git do the work for you:

    if [ `git branch --list $branch_name `]
       echo "Branch name $branch_name already exists."

    I like Heath’s solution, but if you still want to pipe to grep, you can use regex anchors, similar to the following, to preclude matching a substring:

    if [ `git branch | egrep "^[[:space:]]+${branchname}$"` ]
        echo "Branch exists"

    Note that you need to use the space character class because the output of the command is indented.

    Git Baby is a git and github fan, let's start git clone.