在shell中执行函数之前检查函数是否存在

时间:2013-07-31 13:42:07

标签: linux function shell ash

我想在shell脚本中执行函数之前检查函数是否存在。

脚本shell是否支持?以及如何做到这一点?

3 个答案:

答案 0 :(得分:6)

正如this comment所述,这应该是:

type -t function_name

如果它是函数,则返回function

测试

$ type -t f_test
$ 
$ f_test () { echo "hello"; }
$ type -t f_test
function

请注意type提供了良好的信息:

$ type -t ls
alias
$ type -t echo
builtin

答案 1 :(得分:2)

POSIX没有为type内置指定任何参数,并且未指定其输出。除了特定于shell的解决方案之外,您最好的选择可能是

if type foo | grep -i function > /dev/null; then
   # foo is a function
fi

答案 2 :(得分:0)

您可以随时尝试执行该功能。如果它不存在,则该命令的退出状态将为127:

$ myfunction arg1 arg2 || {
>  if [ $? -ne 127 ]; then
>    echo Error with my function
>  else
>    echo myfunction undefined
>  fi; }

当然,该函数可能与另一个二进制文件具有相同的名称,如果该函数没有被该函数遮蔽,您可能不想运行该程序。

相关问题