保留变量值的空间

当在变量的值中使用sapce时,我总是以某种方式很难理解该值。代码如下:

#!/bin/bash

CURL="-H 'accept: application/json' -s -S"

curl ${CURL} https://api.github.com/feeds

使用bash -x执行此操作会导致:

+ CURL='-H '\''accept: application/json'\'' -s -S'
+ curl -H ''\''accept:' 'application/json'\''' -s -S https://api.github.com/feeds
curl: (6) Couldn't resolve host 'application'

我知道空间不是必需的,这只是一个例子。 解决此问题的一种方法是像

一样将空间编码为\x20
#!/bin/bash

CURL="-H accept:\x20application/json"

curl ${CURL} https://api.github.com/feeds

这有效

+ CURL='-H accept:\x20application/json'
+ curl -H 'accept:\x20application/json' https://api.github.com/feeds

但是我发现此解决方案可读性不强。

是否还有另一种在变量的值中引用空格的方式,以便保留该空格并且使字符串(值)易于阅读?

as97100590 回答:保留变量值的空间

这就是数组的用途:存储不容易从单个字符串嵌入或提取的值序列。

curl_opts=(-H "Accept: application/json")

curl "${curl_opts[@]}" https:/api.github.com/feeds
本文链接:https://www.f2er.com/3124079.html

大家都在问