Bash:变量插入curl调用不起作用 [英] Bash: variable insertion into curl call not working

查看:90
本文介绍了Bash:变量插入curl调用不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的bash脚本,其中包含三个命令。

I have a very simple bash script with three commands.

第一个命令将最后一个git commit的第一个单词剥离掉,第二个命令试图使 POST 对api端点的调用,该调用作为变量的一部分,而第三条命令仅打印该变量,以确保其正常工作。参见下面的代码

The first command strips the first word off of the last git commit, the second command attempts to make a POST call to an api endpoint, with that same variable as part of the call, and the third command just prints that variable, to ensure it was working properly. See the code below

SOMETHING=$(git log -1 --pretty=%B | head -n1 | sed -e 's/\s.*$//' | cut -d ' ' -f1)
curl -X POST \
  http://www.someurl.com/ \
  -H 'Cache-Control: no-cache' \
  -d '{"item":"$SOMETHING"}'
echo "variable was $SOMETHING"

当我运行该bash脚本时,我从服务中收到一条响应,说XML中的项目设置不正确,但是正确回显了正确的变量。所以我知道第一行正在工作。如果我复制该curl命令并将其粘贴到bash中,将$ SOMETHING替换为实际值,则可以正常工作。

When I run that bash script, I get a response from the service saying that "item was not set properly" in XML, however it does correctly echo the correct variable. So I know that first line is working. If I copy that curl command and paste it into bash, replacing $SOMETHING with the actual value, it works fine.

推荐答案

单引号不会在其中扩展 $ variables
尝试

Single quotes do not expand the $variables inside them. Try

'{"item":"'"$SOMETHING"'"}'

。简要说明:


  • '{ item:'是一个字符串分隔符由包含双引号的单引号

  • $ SOMETHING 是由双引号分隔的字符串,它扩展了变量 $ SOMETHING

  • '}'再次是' '包含双引号的定界字符串

  • 简单地将这些字符串连续写成无间隙就是字符串串联

  • '{"item":"' is a string delimited by single quotes that contains double quotes
  • "$SOMETHING" is a string delimited by double quotes, that expands the variable $SOMETHING
  • '"}' is again a ''-delimited string that contains double quotes
  • Simply writing those strings in a row without gaps is string concatenation

通过这种方式,您可以进行变量扩展,但不必插入任何反斜杠即可避免双引号。

In this way, you get your variable expansion, but don't have to insert any backslashes to escape the double quotes.

这篇关于Bash:变量插入curl调用不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆