Search code examples
bashgit-bashgithub-cli

Check if github-cli is logged in


I'm working in a bash script using the github cli to create some repos under some conditions but for that I first need to check if the user has the cli installed (and I got that check working) and if it is logged in. gh-cli provides a function gh auth status for that, but I can't use its return to check if the user is logged in. There are two possible outputs:

You are not logged into any GitHub hosts. Run gh auth login to authenticate.

or

    github.com
  ✓ Logged in to github.com as <username> (oauth_token)
  ✓ Git operations for github.com configured to use ssh protocol.
  ✓ Token: *******************

So my first try was to check if there is "not logged" inside that string with:

if [[ $(gh auth status) =~ "not logged" ]] ;
then
    echo "Not logged" ;
    exit 1
fi
#run script

But I had no success. I tried also using grep -oP and sed but then I realized that somehow i can't get the output as a string

Anyone has any suggestions on how to check or fix this?


Solution

  • Use the exit status to determine the success/failure of the installed and logged-in checks:

    1. check it's installed:

      if ! command -v gh >/dev/null 2>&1; then
          echo "Install gh first"
          exit 1
      fi
      
    2. check auth

      if ! gh auth status >/dev/null 2>&1; then
          echo "You need to login: gh auth login"
          exit 1
      fi