如何删除 sh (posix) 中继承的函数
如何确保在运行脚本时不会从父级继承意外的函数?如果使用 bash,
#!/bin/bash -p
就可以解决问题,就像通过 env -i 调用脚本一样。但我不能依赖用户来调用 env,我不想依赖 bash,我不想执行 exec-hack 并重新执行脚本,并且
#!/usr/bin/env -i sh
不起作用。
因此,我正在寻找一种可移植的方式(portable == posix)来确保用户没有定义会意外修改脚本行为的函数。我当前的解决方案是:
eval $( env | sed -n '/\([^=]*\)=(.*/s//\1/p' | while read -r name; do echo unset -f $name\;; done )
但这非常丑陋并且鲁棒性值得怀疑。有没有一种好方法来获取“unset -f -a”应提供的功能?
编辑
稍微不那么难看,但也好不到哪儿去(我不喜欢解析 env 的输出):
unset -f $( env | sed -n '/\([^=]*\)=(.*/s//\1/p' | tr \\012 \ )
How do I ensure that there are no unexpected functions inherited from the parent when my script is run? If using bash,
#!/bin/bash -p
will do the trick, as will invoking the script through env -i. But I cannot rely on the user to invoke env, I don't want to rely on bash, I don't want to do an exec-hack and re-exec the script, and
#!/usr/bin/env -i sh
does not work.
So I'm looking for a portable way (portable == posix) to ensure that the user hasn't defined functions that will unexpectedly modify the behavior of the script. My current solution is:
eval $( env | sed -n '/\([^=]*\)=(.*/s//\1/p' | while read -r name; do echo unset -f $name\;; done )
but that's pretty ugly and of dubious robustness. Is there a good way to get the functionality that 'unset -f -a' should provide?
edit
Slightly less ugly, but no better (I don't like parsing the output of env):
unset -f $( env | sed -n '/\([^=]*\)=(.*/s//\1/p' | tr \\012 \ )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
结果:与
:相同,
并且“sh”是posix...
编辑:
测试了一些函数-在我的情况下不需要取消设置...
编辑2:
比较“set”的输出,而不仅仅是“env”
编辑3:
以下示例 - 两个“set|wc”的输出也给出相同的结果:
results in:
same as:
and "sh" is posix...
EDIT:
tested a few functions - unset was not required in my case...
EDIT2:
compare output of "set", not just "env"
EDIT3:
the following example - output of both "set|wc" also gives same results:
如何使用以下
env
shebang 行设置合理的PATH
变量来调用sh
解释器:How about using the following
env
shebang line that sets a reasonablePATH
variable to invoke thesh
interpreter: