伙计,我讨厌 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\""
}

我以前有过这个头痛,一开始从来没有设法得到这个评估。重要的是, REPORT 变量可能包含多行( \n )。这可能很重要,因为尝试仅用第一行正确替换变量的内容:/

谢谢。

最佳答案

一种风险,不是使用 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

关于ksh 中的 Eval 疯狂,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7001685/

10-12 17:06