bash
4.4引入了一种新的参数扩展类型,它可以做你想做的。即,${[email protected]}
将foo
的值扩展为提示字符串,并且提示字符串在显示之前确实经历了一轮扩展。
${[email protected]}
Parameter transformation. The expansion is either a transforma-
tion 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.
E The expansion is a string that is the value of parameter
with backslash escape sequences expanded as with the
$'...' quoting mechansim.
P The expansion is a string that is the result of expanding
the value of parameter as if it were a prompt string (see
PROMPTING below).
A The expansion is a string in the form of an assignment
statement or declare command that, if evaluated, will
recreate parameter with its attributes and value.
a The expansion is a string consisting of flag values rep-
resenting parameter's attributes.
一个简单的例子:
$ foo='${bar:-9}'
$ echo "$foo"
${bar:-9}
$ echo "${[email protected]}"
9
$ bar=3
echo "${[email protected]}"
3
它,然而,仍允许运行任意命令通过$(...)
:
$ foo='$(echo hi)'
$ echo "${[email protected]}"
hi
另一个警告:确实如此,当然,也拓展迅速如果你的字符串已经包含了一些反斜杠,你可能会进行更多的扩展。快速转义和echo -e
转义之间存在一些冲突。
我不像以前那样是'$ {foo @ P}'的粉丝。我无法分辨命令替换的扩展是一个错误还是一个必要的罪恶。 – chepner
我也很惊讶,命令替换在这里工作。 – hek2mgl
我提交了一个错误报告;至少,手册页应该明确代码执行的可能性。 – chepner