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