1

I am working on a script that creates ssh keys and puts them into github using bash. I am running into this error when running this function.. I want a way to generate ssh keys and put them into github from terminal within my script.

sudo ssh-keygen -t rsa
KEY=$(sudo cat ~/.ssh/id_rsa.pub)
echo "Here is your KEY var: ${KEY}"
read -p "GitHub Username: " USERNAME
read -p "Please enter a title for you ssh key: " TITLE
curl --user "\"${USERNAME}"\" -X POST --data '{ "\"title"\": "\"$TITLE"\", "\"key"\": "\"$KEY"\" }' https://api.github.com/user/keys

Error: { "message": "Bad credentials", "documentation_url": "https://developer.github.com/v3" }

3
  • 1
    Why are you running ssh-keygen as root? Commented Sep 18, 2017 at 23:43
  • That is a really good question lol Commented Sep 18, 2017 at 23:44
  • Repeat after me: sudo is not a magic "make everything work" command. For every command that can be written with sudo, there is a better approach without it. Commented Sep 19, 2017 at 0:01

1 Answer 1

2

You are putting too many quotes in the command. The correct code (to a first approximation) would be

curl --user "${USERNAME}" -X POST \
     --data "{ \"title\": \"$TITLE\", \"key\": \"$KEY\" }" \
     https://api.github.com/user/keys

However this is prone to failure if either TITLE or KEY contains a character that needs to be escaped to include in JSON. The right way to do this is to generate the JSON with a tool like jq, which takes care of any necessary escaping.

curl --user "${USERNAME}" -X POST \
     --data "$(jq -n --arg t "$TITLE" --arg k "$KEY" \
                  '{title: $t, key: $k}')" \
     https://api.github.com/user/keys

or

jq -n --arg t "$TITLE" --arg k "$KEY" '{title: $t, key: $k}' |
  curl --user "$USERNAME" -X POST --data @- https://api.github.com/user/keys
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.