2016-11-14 43 views
0

envsubst人:

這些取代是取代的子集,一個殼 執行上無引號和雙引號字符串。其他種由殼做 取代,如$ {可變默認}$(命令列表)`命令list`,不被envsubst 程序執行時,由於安全原因。

我想執行變量替換字符串,支持如${variable-default}${variable%suffix}的結構。我不想允許運行命令。

顯然這不可能使用envsubst,另一方面eval有嚴重的安全隱患。

除了編寫自定義插值函數之外是否還有其他一些可能性?

回答

3

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轉義之間存在一些衝突。

+2

我不像以前那樣是'$ {foo @ P}'的粉絲。我無法分辨命令替換的擴展是一個錯誤還是一個必要的罪惡。 – chepner

+0

我也很驚訝,命令替換在這裏工作。 – hek2mgl

+3

我提交了一個錯誤報告;至少,手冊頁應該明確代碼執行的可能性。 – chepner

相關問題