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\""
}
我之前头痛的那样,一开始就从来没有成功地进行过评估。这里重要的是,REPORT
var 可能包含多行(\n
's)。这可能很重要,因为其中一次尝试仅用第一行正确替换了变量的内容:/
谢谢。
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 things 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个风险,不是使用 eval,而是使用“varValue”作为 sed 命令中的替换:如果 varValue 包含斜杠,则 sed 命令将中断
如果您的 printf 具有 %q 说明符,这将增加一层安全性 -- % q 转义引号、反引号和美元符号等内容,还转义换行符和制表符等字符:
这是 %q 的示例(这是 bash,我希望您的 ksh 版本对应):
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
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:
Here's an example of what %q does (this is bash, I hope your version of ksh corresponds):