Skip to content

Instantly share code, notes, and snippets.

@iridiumcao
Created March 22, 2020 13:57
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save iridiumcao/714d3d0a9137ce614c26e4e10d185291 to your computer and use it in GitHub Desktop.
Save iridiumcao/714d3d0a9137ce614c26e4e10d185291 to your computer and use it in GitHub Desktop.
How to check if a git branch exists in the local/remote repository?
# Local:
# https://stackoverflow.com/questions/21151178/shell-script-to-check-if-specified-git-branch-exists
# test if the branch is in the local repository.
# return 1 if the branch exists in the local, or 0 if not.
function is_in_local() {
local branch=${1}
local existed_in_local=$(git branch --list ${branch})
if [[ -z ${existed_in_local} ]]; then
echo 0
else
echo 1
fi
}
# Remote:
# Ref: https://stackoverflow.com/questions/8223906/how-to-check-if-remote-branch-exists-on-a-given-remote-repository
# test if the branch is in the remote repository.
# return 1 if its remote branch exists, or 0 if not.
function is_in_remote() {
local branch=${1}
local existed_in_remote=$(git ls-remote --heads origin ${branch})
if [[ -z ${existed_in_remote} ]]; then
echo 0
else
echo 1
fi
}
@pascalandy
Copy link

pascalandy commented May 6, 2022

Thank you :) Here is my version

# Local:
_branch_name="edge"
_check_branch=$(git branch --list ${_check_branch})
# do check Condition_Vars_Must_Be_Not_Empty
if [[ -z ${_check_branch} ]]; then
    echo "local: branch do not exist" > /dev/null 2>&1
else
    echo "local: Good lets continue" > /dev/null 2>&1
fi

# Remote:
_check_branch=$(git ls-remote --heads origin ${_check_branch})
# do check Condition_Vars_Must_Be_Not_Empty
if [[ -z ${_check_branch} ]]; then
    echo "remote: branch do not exist" > /dev/null 2>&1
else
    echo "remote: Good lets continue" > /dev/null 2>&1
fi

# https://twitter.com/askpascalandy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment