10

是否可以覆盖 shell 函数并保留对原始函数的引用?

f()  { echo original; }
f()  { echo wrapper; ...; }
f

这个的输出应该是:

wrapper
original

这可能以半便携式方式吗?

基本原理:我正在尝试通过将部分程序替换为将调用记录到日志文件中的 shell 函数来测试我的程序。只要我只包装命令和内置命令,并且我不介意不分青红皂白的日志记录,它就可以正常工作。现在我想通过只记录每个测试中有趣的部分来使测试套件更易于维护。

所以假设我的程序包括

f
g
h

其中f, g,h都是 shell 函数,我想跟踪 just 的执行情况g

4

2 回答 2

6

Jens 的回答是正确的。只需添加以下代码以确保完整性。

您可以简单地使用它,如下所示:

eval "`declare -f f | sed '1s/.*/_&/'`" #backup old f to _f

f(){
    echo wrapper
    _f # pass "$@" to it if required.
}

我在这里使用了相同的逻辑:https ://stackoverflow.com/a/15758880/793796

于 2013-05-27T15:14:42.733 回答
4

Many shells (zsh, ksh, bash at least) support typeset -f f to dump the contents of f(). Use this to save the current definition to a file; then, define f() as you want. Restore f() by sourcing the file created with typeset.

If you slightly modify the dumped function (renaming f() to _f() on the first line; a bit trickier when f() is recursive or calls other functions you frobbed in the same way), you can likely get this to produce the output you desired.

于 2013-05-27T14:58:12.703 回答