Check if a Git branch exists in remote


Use git ls-remote to list references in a remote repository:

git ls-remote

Check if $BRANCH exists in origin remote:

git ls-remote origin $BRANCH

Use --heads to limit to only refs/heads:

git ls-remote --heads origin $BRANCH

Use --exit-code to exit with status 2 when no matching refs are found in the remote repository:

git ls-remote --exit-code --heads origin $BRANCH
echo $?

Thus, to check if variable $BRANCH exists in the remote repository:

#!/bin/bash

BRANCH='my-branch-name'
git ls-remote --exit-code --heads origin $BRANCH >/dev/null 2>&1
EXIT_CODE=$?

if [[ $EXIT_CODE == '0' ]]; then
  echo "Git branch '$BRANCH' exists in the remote repository"
elif [[ $EXIT_CODE == '2' ]]; then
  echo "Git branch '$BRANCH' does not exist in the remote repository"
fi


Please support this site and join our Discord!