Skip to content

Instantly share code, notes, and snippets.

@tiborsimon
Created March 19, 2016 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiborsimon/4394e500f43d59bf35a5 to your computer and use it in GitHub Desktop.
Save tiborsimon/4394e500f43d59bf35a5 to your computer and use it in GitHub Desktop.
Upload your ssh key to GitHub via the GitHub API
#!/bin/sh
#
# This script will upload your pre-generated ssh key to your GitHub account using the GitHub API.
# Make sure you set up the GITHUB_USERNAME and SSH_KEY variables before you run the script.
#
# Corresponding article: https://tiborsimon.io/programming/upload-ssh-key-via-github-api/
#
# Created by Tibor Simon 2016
GITHUB_USERNAME=tiborsimon
SSH_KEY=$HOME/.ssh/id_rsa
if [ ! -f $SSH_KEY ] || [ ! -f $SSH_KEY.pub ]; then
echo 'Generate your ssh key first!'
exit
fi
github_result=0
echo 'How do you want to name the key?'
read -e KEY_NAME
until [ $github_result -eq 1 ]; do
curl --silent -u "$GITHUB_USERNAME" --data "{\"title\":\"$KEY_NAME\",\"key\":\"$(cat $SSH_KEY.pub)\"}" https://api.github.com/user/keys > gh-result
if grep -q 'key is already in use' gh-result; then
github_result=1
echo 'Key is already in use.'
elif grep -q '"verified": true' gh-result; then
github_result=1
echo "Key ($KEY_NAME) has been added successfully."
elif grep -q 'Bad credentials' gh-result; then
echo 'Error during login: invalid username or password!'
echo 'Try again!'
else
echo 'A problem occured during the upload!'
cat gh-result
echo 'Try again!'
fi
rm gh-result
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment