开发者

Eval madness in ksh

Man I hate eval...

I'm stuck with this ksh, and it has to be this way.

There's this function I need, which will receive a variable name and a value. Will do some t开发者_StackOverflow社区hings to the contents of that variable and the value and then would have to update the variable that was received. Sort of:

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

setOutputReport REPORT "this"

echo $REPORT
a text where this is wrong..

Where the function would be something like

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\""
}

I had this headache before, never manage to get this eval right at first. Important here, the REPORT var may contain multiple lines (\n's). This might be important as one of the attempts managed to correctly replace the contents of the variable with the fist line only :/

thanks.


One risk, not with eval but with the "varValue" as the replacement in the sed command: if varValue contains a slash, the sed command will break

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

If your printf has the %q specifier, that will add a layer of security -- %q escapes things like quotes, backticks and dollar signs, and also escaped chars like newline and tab:

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

Here's an example of what %q does (this is bash, I hope your version of ksh corresponds):

$ 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜