测试某个函数是否可以使用

Ver*_*era 4 bash

如果函数所在的文件尚未被获取,是否可以测试该函数是否可以使用?

Sté*_*las 5

bash(或ksh该语法的来源,或zsh\xc2\xb9)中,您可以执行以下操作:

\n
if typeset -f myfunction > /dev/null; then\n  echo The myfunction function is defined\nfi\n
Run Code Online (Sandbox Code Playgroud)\n

这也适用于 ksh(该语法来自于此)和 zsh。

\n

在 中zsh,您还可以执行以下操作:

\n
if (( $+functions[myfunction] )) then\n  echo The myfunction function is defined\nfi\n
Run Code Online (Sandbox Code Playgroud)\n

这是测试将函数名称映射到其定义的特殊关联数组中是否存在myfunction(两种方法也适用于尚未加载的可自动加载函数)。

\n

请注意,如果碰巧也有一个别名,为了能够使用相同名称的函数,您必须引用它或至少引用它的一部分(而'cmd' args不是cmd args)。同样的情况也适用于 shell 保留字,但 bash 无论如何都不允许您定义与保留字同名的函数。

\n

正如 @JJao 在评论中所建议的,您还可以使用type -t(在 bash 或最新版本的 ksh93 中)来告诉您命令的类型myfunction

\n
case $(type -t myfunction) in\n  (function) echo OK;;\n  (alias) echo might exist as a function but it is first an alias;;\n  (*) echo cannot be used as a function;;\nesac\n
Run Code Online (Sandbox Code Playgroud)\n
\n

\xc2\xb9 与yash,API 略有不同,定义函数时typeset -f myfunction返回true且不产生任何输出,否则返回false并输出错误消息。您需要typeset -pf myfunction在 yash 中打印函数的定义(也可以在 ksh/zsh/bash 中使用,尽管-p在那里不是必需的)。所以,你需要if typeset -f myfunction 2> /dev/null。这样做if typeset -f myfunction > /dev/null 2>&1将使其可移植到所有四个 shell。

\n