我用谷歌搜索并尝试了很多东西,但从来没有得到任何与 ${parameter@operator} 一起工作的东西。我找到的只是指向同一文档的更多链接。因此,我认为通过实际示例进行适当的回答将非常有助于理解它。
文档说:
${parameter@operator}
The expansion is either a transformation of the value of parameter or information about parameter itself, depending on the value of operator. Each operator is a single letter:
Q
The expansion is a string that is the value of parameter quoted in a format that can be reused as input.
它还提到了引用:
3.1.2 Quoting
Quoting is used to remove the special meaning of certain characters or words to the shell.
所以我的推理是这个(特殊字符$)的输出:
a="To be reused as an input string, \$0 needs to be quoted"
echo ${a@Q}
应该是这样的(在“”之间,'\'被删除,所以需要再次引用以用作输入):
To be reused as an input string, \$0 needs to be quoted
但我得到:
bash: ${a@Q}: bad substitution
我尝试了不同的组合:
${a@q}, "${a@Q}", a='To be reused as an input string, $0 needs to be quoted'
没用。
实际上,我尝试使用的任何运算符总是会产生错误的替换错误。这些似乎是 bash 非常晦涩的特性。我从这篇文章中省略了大约半小时的尝试,每一次都比前一次更扭曲!
最佳答案
对于那些来到这里寻找有关不同扩展运算符的信息的人,这里有一个可用扩展字符及其效果的快速列表。
${varname@Q}
返回带有任何特殊字符(例如\n、\t、等)逃脱了。
例子:
$ foo="one\ntwo\n\tlast"
$ echo "$foo"
one\ntwo\n\tlast
$ echo ${foo@Q}
'one\ntwo\n\tlast'
${varname@E}
返回所有转义字符 Expanded(例如\n -> 换行符)的字符串。
例子:
$ foo="one\ntwo\n\tlast"
$ echo "${foo}"
one\ntwo\n\tlast
$ echo "${foo@E}"
one
two
last
${varname@P}
返回一个字符串,该字符串显示变量在用作 Prompt 变量时的样子(即 PS1、PS2、PS3)
例子:
$ bar='host: \h'
$ echo ${bar@P}
host: myhost1
(可以在提示变量中应用更多的转义序列。请参阅 bash documentation。)
${varname@A}
返回一个字符串,该字符串可用于A用变量的现有名称、值和声明
选项(如果有的话)。
例子:
$ foo="test1"
$ echo ${foo@A}
foo='test1'
$ declare -i foo=10
$ echo "${foo@A}"
declare -i foo='10'
${varname@a}
返回一个字符串,列出变量的 A属性。
例子:
$ declare -ir foo=10
$ echo ${foo@a}
ir
(可用的声明选项有:-r
readonly,-i
integer,-a
array,-f
函数,-x
可导出。)
关于Bash:如何使用运算符参数扩展${parameter@operator}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40732193/