Using cURL to send JSON within a BASH script

17,908

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.

Share:
17,908
Wilhelm Murdoch
Author by

Wilhelm Murdoch

Updated on June 05, 2022

Comments

  • Wilhelm Murdoch
    Wilhelm Murdoch almost 2 years

    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!

  • Wilhelm Murdoch
    Wilhelm Murdoch over 12 years
    You are a gentleman and a scholar. I had to learn all this stuff in quite a rush, so I don't really fully grasp proper escaping and string manipulation in Bash just yet. Thanks for that!
  • shellter
    shellter over 12 years
    I commend you sir for your insight and keen analytical skills! Continued success in your endeavors! ;-)
  • Brian
    Brian about 9 years
    Thank you very much! There are a few other responses to similar questions which are incorrect. This is just what I needed!
  • Smaïne
    Smaïne over 3 years
    8 yeasrs later it help me TY !