Created
March 25, 2021 16:51
-
-
Save chrisgfortes/ccfdd8457270bd51090b23f84def6dd4 to your computer and use it in GitHub Desktop.
How to check if a git branch exists in the local/remote repository?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 1. To check the branch in the local 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 | |
} | |
# 2. To check the branch in the remote repository | |
# 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 | |
} | |
## Reference: | |
## - https://dev.to/iridiumcao/how-to-check-if-a-git-branch-exists-in-the-local-remote-repository-3gkd | |
## - https://gist.github.com/iridiumcao/714d3d0a9137ce614c26e4e10d185291 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment