Bash中带引号修饰符的带引号参数扩展 [英] Quoted parameter expansion with quoted modifier in Bash

查看:77
本文介绍了Bash中带引号修饰符的带引号参数扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到了一些奇怪的事情:

I've noticed something weird:

Y=""
echo ${Y:-"\n"}
echo "${Y:-"\n"}"

打印

\n
n

为什么第二行是 n ,而不是 \ n ?这是一个错误吗?

Why is the second line n, not \n? Is this a bug?

似乎Bash将此解析为两个带引号的字符串的串联,而两个引号之间有一个未加引号的字符串("$ {Y:-" \ n }" ),但自命令以来似乎并非如此

It looks as if Bash parsed this as a concatenation of two quoted strings with an unquoted string in between ("${Y:-" and \n and "}") but this doesn't seem to be the case since the commands

echo $(echo "\n")
echo "$(echo "\n")"
echo "${Y:-"'\n'"}"

输出

\n
\n
'n'

我正在使用GNU bash版本4.3.11.

I'm using GNU bash, version 4.3.11.

推荐答案

我怀疑在:-之后的单词处理过程中存在错误(实际上,我似乎还记得阅读过一些有关这个,但我不记得在哪里.)

I suspect there is a bug in the handling of the word following :- (in fact, I seem to recall reading something about this, but I can't recall where).

如果该值未加引号,我会得到预期的结果...

If the value is not quoted, I get results I would expect...

$ echo ${Y:-\n}
n
$ echo "${Y:-\n}"
\n

这也是您在 dash 中得到的结果(忽略了 dash 实际上产生原义换行符的事实,因为POSIX要求 echo 应该处理转义字符,仅当您使用非标准的 -e 选项时, bash 才起作用.)

This is also the result you get in dash (ignoring the fact that dash actually produces a literal newline since POSIX mandates that echo should process escaped characters, something bash only does if you use the non-standard -e option.)

在此示例中,引用默认值将保留反斜杠.由于参数扩展的结果产生反斜杠,因此引号删除不会删除它.

In this example, quoting the default value preserves the backslash. As the result of the parameter expansion produces the backslash, quote removal does not remove it.

$ echo ${Y:-"\n"}   # Equivalent to echo "\n", so the output makes sense
\n

在最后一个示例中,似乎没有任何理由使 bash 表现出不同,只是因为整个参数扩展都被引用了.好像两次都执行了引号删除操作,一次是删除外部双引号,另一次是不正确地删除了反斜杠.

There doesn't seem to be any reason for bash to behave different in this final example just because the entire parameter expansion is being quoted. It is almost as if quote removal is being applied twice, once to remove the outer double quotes and again to incorrectly remove the backslash.

# Quote removal discards the backslash: OK
$ echo \n
n
# Quote removal discards the double quotes: OK
$ echo "n"
n
# Quote removal discards the first backslash after `\\` is recognized
# as a quoted backslash: OK
$ echo \\n
\n 
# Quote removal discards the double quotes, but leaves
# backslash: OK
$ echo "\n"
\n
# Is quote removal discarding both the double quotes *and* the backslash? Not OK
$ echo "${Y:-"\n"}"
n

相关的 zsh (带有 bsd_echo )选项设置输出 \ n ,而不是 n .

Related, zsh (with the bsd_echo) option set outputs \n, not n.

% Y=""
% echo "${Y:-"\n"}"
\n

这篇关于Bash中带引号修饰符的带引号参数扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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