Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Safely check if public GitHub repo exists in bash without login?

Context

While trying out the answer provided in this question on how to check if a GitHub repository exists using bash, I notice that the command asks for credentials and throws an error if the repository is not found:

git ls-remote https://github.com/some_git_user/some_non_existing_repo_name -q
Username for 'https://github.com': some_git_user 
Password for 'https://some_git_user@github.com': 
remote: Repository not found.
fatal: repository 'https://github.com/some_git_user/some_non_existing_repo_name/' not found
(base) somename@somepcname:~$ echo $?
128

This answer seems to prevent git from asking credentials.

Issues

  1. Being asked for credentials is fine in other scenarios, so I would prefer to not disable git from asking credentials system-wide. Yet still, I would like the function to run automatically without asking for credentials, as they are not needed for a check to a public repository.
  2. The command yields an error status 128 if it does not find the repository. Instead, I would like to safely check if the repository is found or not, without raising an error. E.g. by producing outputs echo "FOUND" or echo "NOTFOUND".

Question

How can one test if a public GitHub repository exists in bash, without being prompted for credentials, without raising an error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Details

The user has not provided any ssh-key nor credentials to/in the script.

>Solution :

In order to easily check if a public repository exists on GitHub, you actually need not git nor any credentials: you can make a simple HTTP request to the GitHub REST API.

Proof-of-concept:

#!/usr/bin/env bash
exists_public_github_repo() {
  local user_slash_repo=$1

  if curl -fsS "https://api.github.com/repos/${user_slash_repo}" >/dev/null; then
    printf '%s\n' "The GitHub repo ${user_slash_repo} exists." >&2
    return 0
  else
    printf '%s\n' "Error: no GitHub repo ${user_slash_repo} found." >&2
    return 1
  fi
}


if exists_public_github_repo "ocaml/ocaml"; then
  echo "OK"
fi

For more details on the curl command itself and the flags -f, -s, -S I used, you can browse its man page online.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading