开发者

How to remove inherited functions in sh (posix)

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 '/\([^=]*\)=(.开发者_Go百科*/s//\1/p' | tr \\012 \  )


#!/bin/bash --posix 

results in:

SHELLOPTS=braceexpand:hashall:interactive-comments:posix

same as:

#!/bin/sh

SHELLOPTS=braceexpand:hashall:interactive-comments:posix

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:

#!/bin/sh

set
set|wc

unset -f $( env | sed -n '/\([^=]*\)=(.*/s//\1/p' | tr \\012 \  )

set
set|wc


How about using the following env shebang line that sets a reasonable PATH variable to invoke the sh interpreter:

#!/usr/bin/env -i PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/xpg4/bin sh
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜