在ksh的Eval疯狂

时间:2011-08-09 19:18:42

标签: eval ksh

我讨厌eval ...

我坚持使用这个ksh, 就是这样。

我需要这个功能,它将接收变量名称和值。将对该变量的内容和值做一些事情,然后必须更新收到的变量。排序:

REPORT="a text where TADA is wrong.."

setOutputReport REPORT "this"

echo $REPORT
a text where this is wrong..

其中的功能类似于

function setOutputReport {
    eval local currentReport=\$$1
    local reportVar=$1
    local varValue=$2

    newReport=$(echo "$currentReport"|sed -e 's/TADA/$varValue')

    # here be dragons
    eval "$reportVar=\"$newReport\""
}

我之前有过这样的头痛,从来没有设法让这个eval正确。重要的是,REPORT var可能包含多行(\n)。这可能很重要,因为其中一个尝试设法用第一行正确替换变量的内容:/

感谢。

1 个答案:

答案 0 :(得分:2)

一个风险,不是使用eval而是使用“varValue”作为sed命令中的替换:如果varValue包含斜杠,则sed命令将中断

local varValue=$(printf "%s\n" "$2" | sed 's:/:\\/:g')
local newReport=$(echo "$currentReport"|sed -e "s/TADA/$varValue/")

如果你的printf有%q说明符,那么会增加一层安全性 - %q会丢弃引号,反引号和美元符号之类的东西,还会转换像换行符和制表符这样的字符:

eval "$(printf "%s=%q" "$reportVar" "$newReport")"

以下是%q的例子(这是bash,我希望您的ksh版本对应):

$ y='a `string` "with $quotes"
with multiple
lines'
$ printf "%s=%q\n" x "$y"
x=$'a `string` "with $quotes"\nand multiple\nlines'
$ eval "$(printf "%s=%q" x "$y")"
$ echo "$x"
a `string` "with $quotes"
and multiple
lines