卷曲引号和变量麻烦 [英] Curl quotes and variable trouble

查看:44
本文介绍了卷曲引号和变量麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从读取主机名文件的shell脚本中运行curl命令.这是不起作用的脚本:

I need to run a curl command from a shell script that reads a file of host names. Here is the script that does not work:

#!/bin/sh

HOST="HOSTNAME"

curl https://SOME_URL -H 'Content-Type: application/json' -H 'API-Key: SOME_KEY' --data-binary '{"query":"{\n  actor {\n    entitySearch(query: \"name LIKE \u0027$HOST\u0027\") {\n      results {\n        entities {\n          guid\n        }\n      }\n    }\n  }\n}\n", "variables":""}'

问题是名称LIKE \ u0027 $ HOST \ u0027

单引号字符需要 \ u0027 .

如果我使用实际的主机名而不是变量,则可以正常工作.

If I use an actual host name instead of the variable it works fine.

我尝试在变量周围使用花括号,但这不起作用.

I tried curly braces around the variable and that doesn't work.

推荐答案

问题是由于您使用单引号'发送您的-data-binary 字段.按照设计,bash变量不会在单引号内扩展.您可以反转单引号和双引号的用法,也可以通过在bash变量周围放置单引号来简单地连接扩展变量,例如:

The issue is because of your use of a single quotes ' to send your --data-binary field. By design, bash variables are not expanded inside of single quotes. You could either reverse your usage of single and double quotes, or simply concatenate the expanded variable by placing single quotes around your bash variable, as such:

curl https://SOME_URL -H 'Content-Type: application/json' -H 'API-Key: SOME_KEY' --data-binary '{"query":"{\n  actor {\n    entitySearch(query: \"name LIKE \u0027'$HOST'\u0027\") {\n      results {\n        entities {\n          guid\n        }\n      }\n    }\n  }\n}\n", "variables":""}

作为附加说明,最好封装bash变量,该变量表示双引号内的字符串,例如"$ HOST".这是因为如果bash变量不存在,则该变量后面的文本将被删除;但是,引用不存在的带引号的bash变量只会返回一个空字符串,而不是删除命令的其余部分.我将上面的解决方案保留为未加引号的形式,以便更轻松地查看更改,但是在脚本中使用加引号的形式是一种很好的做法.

As an additional note, it is preferred to encapsulate bash variables representing strings inside of double quotes, such as "$HOST". This is because the text following a reference to a bash variable is removed if that variable does not exist; however, referencing a quoted bash variable that doesn't exist will simply return an empty string instead of removing the rest of the command. I've left the solution above in the unquoted form so it is easier to see the changes, but it is good practice to use the quoted form in scripts.

这篇关于卷曲引号和变量麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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