0

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
Lev Shapiro
  • 69
  • 1
  • 7
  • What about https://stackoverflow.com/questions/11231937/bash-ignoring-error-for-a-particular-command ? – Martin Tovmassian May 12 '22 at 15:27
  • git ls-remote https://github.com/user/repository || true? Still I have an error – Lev Shapiro May 12 '22 at 15:31
  • remote: Repository not found. fatal: repository 'https://github.com/user/repo/' not found – Lev Shapiro May 12 '22 at 15:31
  • 2
    Id use curl/wget etc to look for a 404 which might be a better option `if [[ $(curl -s -o /dev/null -w "%{http_code}" https://github.com/user/repository) == 404 ]]` else your need to sign in or setup public keys before hand which then you might a well create the repo via github anyway – Lawrence Cherone May 12 '22 at 15:44
  • @LevShapiro, are you using `https://github.com/user/repository` as the repo URL in your code? Try updating your code to use a repository that you know exists and that you have access to. (I do not think there is a repo with the URL `https://github.com/user/repository`) – j_b May 12 '22 at 15:45
  • @j_b https://github.com/user/repository is just example. I use user as my account name and repository as repository name – Lev Shapiro May 12 '22 at 15:52
  • @LawrenceCherone, great idea, works as needed – Lev Shapiro May 12 '22 at 15:55

1 Answers1

2

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 
Martin Tovmassian
  • 1,010
  • 1
  • 10
  • 19