Shell script to check if specified Git branch exists? [duplicate] Shell script to check if specified Git branch exists? [duplicate] git git

Shell script to check if specified Git branch exists? [duplicate]


NOTE: This always returns true. This is not the right answer to the question, even though it has been accepted....

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.