How to check if remote branch exists on a given remote repository?

$ git ls-remote --heads [email protected]:user/repo.git branch-name

In case branch-name is found you will get the following output:

b523c9000c4df1afbd8371324083fef218669108        refs/heads/branch-name

Otherwise no output will be sent.

So piping it to wc will give you 1 or 0:

$ git ls-remote --heads [email protected]:user/repo.git branch-name | wc -l

Alternatively you can set --exit-code flag on git ls-remote which will return exit code 2 in case no matching refs are found. The result can be checked directly in a shell test or by checking the status variable $?.

$ git ls-remote --exit-code --heads [email protected]:user/repo.git branch-name

Leave a Comment