Using cURL to send JSON within a BASH script

2019-03-19 04:34发布

问题:

Alright, here's what I'm trying to do. I'm attempting to write a quick build script in bash that will check out a private repository from GitHub on a remote server. To do this a "hands off" as possible, I want to generate a local RSA key set on the remote server and add the public key as a Deploy Key for that particular repository. I know how to do this using GitHub's API, but I'm having trouble building the JSON payload using Bash.

So far, I have this particular process included below:

#!/bin/bash

ssh-keygen -t rsa -N '' -f ~/.ssh/keyname -q
public_key=`cat ~/.ssh/keyname.pub`

curl -u 'username:password' -d '{"title":"Test Deploy Key", "key":"'$public_key'"}' -i https://api.github.com/repos/username/repository/keys

It's just not properly building the payload. I'm not an expert when it comes to string manipulation in Bash, so I could seriously use some assistance. Thanks!

回答1:

It's not certain, but it may help to quote where you use public_key, i.e.

curl -u 'username:password' \
   -d '{"title":"Test Deploy Key", "key":"'"$public_key"'"}' \
   -i https://api.github.com/repos/username/repository/keys

Otherwise it will be much easier to debug if you use the shell's debugging options set -vx near the top of your bash script.

You'll see each line of code (or block (for, while, etc) as it is in your file. Then you see each line of code with the variables expanded to their values.

If you're still stuck, edit your post to show the expanded values of variables for the problem line in your script. What you have looks reasonable at first glance.