为什么JSON字符串会使用bash shell进行转换 [英] Why JSON strings transform with bash shell

查看:499
本文介绍了为什么JSON字符串会使用bash shell进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

$ export foo=["foo","zoom"]
$ echo $foo
[foo,zoom]
$ export foo='["foo","zoom"]'
$ echo $foo
["foo","zoom"]

如果我不使用单引号引起来,为什么(双引号)字符被删除?

why is it that the " (double quote) chars get removed if I don't wrap in single quotes?

推荐答案

请考虑以下问题:

$ echo "foo"
foo

我们注意到该字符串中没有任何引号.从 bash手册:

We notice that there aren't any quotes in that string. From the bash manual:

用双引号(')引起来的字符会保留原义 引号中所有字符的值,"$"除外, ‘`’,‘\’,

Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’,

所以双引号是bash语法.要获取文字双引号,我们需要对其进行转义:

So double quotes are bash syntax. To get literal double quotes we need to escape them:

$ echo \"foo\"
"foo"

转义的另一种方法是使用单引号(同样来自bash手册):

Another option to escaping is to use single quotes (again from the bash manual):

用单引号('')引起来的字符会保留原义 引号中每个字符的值.

Enclosing characters in single quotes (‘'’) preserves the literal value of each character within the quotes.

所以这等效于上面的命令:

So this is equivalent to the above command:

$ echo '"foo"'
"foo"

在您的特定示例中,我们可以看到以下内容:

Applied to your specific example, we can see this:

$ export foo=["foo","zoom"]
$ declare -p foo
declare -- foo="[foo,zoom]"

双引号被解析掉.

但是

$ export foo='["foo","zoom"]'
$ declare -p foo
declare -x foo="[\"foo\",\"zoom\"]"

单引号与转义双引号具有相同的作用.

The single quotes have the same effect as escaping the double quotes.

这篇关于为什么JSON字符串会使用bash shell进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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