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

  • Centralized GIT workflow/deployment - Release Branch
  • jenkins shall fail on errors during rpm install job
  • Shell Script Sequencing with Rake
  • How do I write a batch file which opens the GitBash shell and runs a command in the shell?
  • Interpreting GIT's Branching Summary
  • Curl Initialization error with git pre-push hook
  • clearcase: Backup for only modified checked-out elements in all views
  • bash git pre-commit hook running MatLab function does not wait for a result
  • 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 `]
    then
       echo "Branch name $branch_name already exists."
    fi
    

    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}$"` ]
    then
        echo "Branch exists"
    fi
    

    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.