防止bash向变量输出添加单引号 [英] Prevent bash from adding single quotes to variable output

查看:40
本文介绍了防止bash向变量输出添加单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:我正在编写一个使用 curl 执行多个 HTTP 请求的脚本,我想将标头添加到一个变量 CURL_HEADERS 中,这样我就不必键入它们不断地出来.当我在 curl 命令中回显 CURL_HEADERS 变量时,单引号出现在我不想要的地方.我怎样才能防止这种情况?(为了清楚起见,下面的代码被简化了)

Problem: I'm writing a script that performs several HTTP requests with curl and I want to add the headers to a variable, CURL_HEADERS, so that I don't have to type them out constantly. When I echo the CURL_HEADERS variable in the curl command, single quotations appear where I don't want them. How can I prevent this? (The code below is simplified for the sake of clarity)

代码

#!/usr/bin/env bash
AUTH_KEY='1234'
set -x
CURL_HEADERS='-H "Authorization: Basic '${AUTH_KEY}'" -H "Content-Type: application/json"'
echo "${CURL_HEADERS}"
curl -s $(echo "${CURL_HEADERS}") 'http://www.example.org' > /dev/null
set +x

预期输出:

+ CURL_HEADERS='-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
+ echo '-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
-H "Authorization: Basic 1234" -H "Content-Type: application/json"
++ echo '-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
+ curl -s -H "Authorization: Basic 1234" -H "Content-Type: application/json" http://www.example.org
+ set +x

实际输出

+ CURL_HEADERS='-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
+ echo '-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
-H "Authorization: Basic 1234" -H "Content-Type: application/json"
++ echo '-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
+ curl -s -H '"Authorization:' Basic '1234"' -H '"Content-Type:' 'application/json"' http://www.example.org
+ set +x

推荐答案

一个相当简单的解决方案是使用 bash 数组来存储您要传递的四个参数:

A reasonably straightforward solution is to use a bash array to store the four arguments you will want to pass:

CURL_HEADERS=(
             '-H' "Authorization: Basic ${AUTH_KEY}"
             '-H' 'Content-Type: application/json'
)

curl -s "${CURL_HEADERS[@]}" 'http://www.example.org' > /dev/null

与标量变量不同,标量变量只是普通字符的普通字符串,无论它们可能包含多少引号,数组是字符串列表,每一个都相互区分.从这个意义上说,bash 就像几乎所有其他编程语言一样.

Unlike scalar variables, which are just ordinary strings of ordinary characters no matter how many quotes they might contain, arrays are lists of strings, each one distinguished from each other one. In this sense, bash is just like almost every other programming language.

这个问题,以及我建议的解决方案以及其他几个问题,在 Bash FAQ entry 50 (我试图将命令放入变量中,但复杂的情况总是失败!),值得详细阅读.(链接来自@John1024 的评论.)

This problem, and the solution I suggest as well as several other ones, is well-described in the Bash FAQ entry 50 (I'm trying to put a command in a variable, but the complex cases always fail!), which is worth reading in detail. (Link taken from a comment by @John1024.)

这篇关于防止bash向变量输出添加单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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