I need to create a Git branch using shell script, but since the branch may exist, I need to be aware of that. Currently I'm using:
if [ `git branch | grep $branch_name` ] then echo "Branch named $branch_name already exists" else echo "Branch named $branch_name does not exist" fi
But the problem is the grep
command finds branch name without matching the exact name, that is, if I grep name
then branch with a name branch-name
would be matched.
So is there a better way to do this?
Thanks!
In order to compare two branches easily, you have to use the “git diff” command and provide the branch names separated by dots. Using this command, Git will compare the tip of both branches (also called the HEAD) and display a “diff” recap that you can use to see modifications.
Let's call it git is_localbranch (you need to add alias in .gitconfig ). git branch | grep -w $1 > /dev/null if [ $? = 0 ] then echo "branch exists" fi
We can use " -d " attribute to check if a directory exists in shell programming. We can use -d attribute within single [..] or double brackets [ [..]] to check if directory exists. Similarly we use single brackets in this example to check if the directory is preset within shell script.
Similarly using test command to check if regular file exists in bash or shell script in single line. 2. Bash/Shell: Check if file exists (is empty or not empty) To check if the file exists and if it is empty or if it has some content then we use " -s " attribute Check if file exists and empty or not empty using double brackets [ [..]]
If the branch exists the content of the branchExist variable would be something like: To verify if a branch exists on remote, this worked fine to me: git branch -r | grep -qn origin/$ {GIT_BRANCH_NAME}$ && echo "branch exists" || echo "branch does not exists" Note that <repo_url> can just be a "."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With