具有不同名称的导出函数

jes*_*e_b 4 bash

我有一个脚本,它导出一个函数供子脚本使用,并且想根据条件更改导出的函数。我知道我可以在条件中声明两个不同的函数,但如果可能的话我宁愿避免这种情况。

所以一个例子是:

#!/bin/bash

foo () { echo foo; }
bar () { echo bar; }

if [[ $var == foo ]]; then
    #in this case my_func() should execute foo()
    export -f my_func
elif [[ $var == bar ]]; then
    #in this case my_func() should execute bar()
    export -f my_func
fi
Run Code Online (Sandbox Code Playgroud)

我想我也可以my_func() { foo "$@"; }在导出之前创建一个简单的起始函数,就像在条件内部一样,但我询问是否有更好的方法来做到这一点。

Kus*_*nda 5

这可能是您已经提议的,但我认为没有更好的方法。shell 没有提供一种安全的内省方式来在的声明中包含预先声明的实际声明foo或函数,我认为这是一种替代方法。如果您不愿意将或 的功能移入(即,不创建或作为单独的功能),那么我在这里展示的可能是最好的:barmy_funcfoobar my_funcfoobar

#!/bin/bash

foo () { echo foo; }
bar () { echo bar; }

case $var in
    foo) export -f foo; my_func () { foo "$@"; } ;;
    bar) export -f bar; my_func () { bar "$@"; } ;;
esac

export -f my_func
Run Code Online (Sandbox Code Playgroud)

也就是说,根据 的值var,导出您正在使用的适当函数my_func并声明您的函数。然后导出。