2016-11-14 39 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

相关问题