Home > Blockchain >  Bash - check if repository exists
Bash - check if repository exists

Time:05-13

I am trying to create if statement which will check if repository with name X exists, if it doesn't => create it.

Made following code. It works, but when repository doesn't exists, then it shows error. I couldn't find any ways of removing that error in console. Make I was using &>/dev/null not in correct way...

    myStr=$(git ls-remote https://github.com/user/repository);
    if [ -z $myStr ]
    then
        echo "OMG IT WORKED"
    fi

CodePudding user response:

As soon as you completely silence git ls-remote I will suggest to check the exit code of the command ($?) rather than its output.

Based on your code you could consider a function in this way:

check_repo_exists() {
    repoUrl="$1"
    myStr="$(git ls-remote -q "$repoUrl" &> /dev/null)";
    if [[ "$?" -eq 0 ]]
    then
        echo "REPO EXISTS"
    else
        echo "REPO DOES NOT EXIST"
    fi
}

check_repo_exists "https://github.com/kubernetes"
# REPO DOES NOT EXIST
check_repo_exists "https://github.com/kubernetes/kubectl"
# REPO EXISTS 
  • Related