Access GitHub API with a simple bash script

Intro

I wrote this simple bash script, that uses the GitHub API, to get profile information e.g. of Google's GitHub Account. https://api.github.com/users/google

You could replace "google" with any GitHub username to retrieve information about them:

https://api.github.com/users/<username>

We are going to use that option to write our script. Let's start.

The Script

Our script will accept only one argument, which is the GitHub username. So we need to make sure, that the user doesn't type less or more than one argument. That can be solved with a simple if-condition.

# check for user argument
if [ $# -ne 1 ]; then
  echo "Usage: $0 <username>"
  exit 1
fi

We can access the API with a curl command. To avoid multiple API calls, we are going to execute the curl command only once. So we need to retrieve all the data and save it as a JSON-file. Before that, we need to make sure, that the JSON-File doesn't exist and if so, then it should be deleted.

# check for existing json file...if found, then delete it.
tmp_json=tmp_githubinfo.json;
if [ -f "$tmp_json" ]; then
    rm $tmp_json
fi

Now comes the main part. We are executing the curl command and save the result to our JSON-File

curl -s "https://api.github.com/users/$1" >> $tmp_json

With the function "getInfo()" we are able to retrieve any information that is stored there. The tool 'jq' allows us to search for any fields we want.

function getInfo() {
    cat $tmp_json | jq -r "$1"
}

So e.g. if you want to know, how many followers a certain GitHub user has, then just execute this command:

echo -e "Followers: " $(getInfo ".followers")

That's it. This is the result you'll get, when you execute the script:

$ ./githubinfo.sh google
Name:  Google
URL:  https://github.com/google
Company:  null
Website:  https://opensource.google/
E-Mail:  opensource@google.com
Followers:  0
Following:  0
Created at:  2012-01-18T01:30:18Z
Last updated:  2021-09-17T16:51:41Z

The full script can be found here: https://github.com/senthusiva/script-toolbox/blob/main/src/githubinfo.sh

Download it and try it out. Your feedback is welcome.



Senthu © 2023. Code adapted from the Next.js example provided by Vercel under the MIT license here.