使用 cURL 在 BASH 脚本中发送 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8903222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:20:21  来源:igfitidea点击:

Using cURL to send JSON within a BASH script

bashcurlsshgithub

提问by Wilhelm Murdoch

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.

好的,这就是我正在尝试做的。我正在尝试用 bash 编写一个快速构建脚本,该脚本将从远程服务器上的 GitHub 上检出一个私有存储库。为了尽可能地做到这一点,我想在远程服务器上生成一个本地 RSA 密钥集,并将公钥添加为该特定存储库的部署密钥。我知道如何使用 GitHub 的 API 执行此操作,但是我在使用 Bash 构建 JSON 有效负载时遇到了问题。

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!

它只是没有正确构建有效负载。我不是 Bash 中字符串操作的专家,所以我可以认真地使用一些帮助。谢谢!

回答by shellter

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

不确定,但引用您使用 public_key 的位置可能会有所帮助,即

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 -vxnear the top of your bash script.

否则,如果您set -vx在 bash 脚本顶部附近使用 shell 的调试选项,调试会容易得多。

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.

您将看到文件中的每一行代码(或块(for、while 等)。然后您会看到每一行代码都将变量扩展为它们的值。

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.

如果您仍然卡住,请编辑您的帖子以显示脚本中问题行的变量的扩展值。乍一看,您拥有的东西看起来很合理。