判断函数是否存在于bash中 [英] Determine if a function exists in bash

查看:25
本文介绍了判断函数是否存在于bash中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在做一些从 bash 执行的单元测试.单元测试在 bash 脚本中初始化、执行和清理.这个脚本通常包含一个 init()、execute() 和 cleanup() 函数.但它们不是强制性的.我想测试它们是否已定义.

Currently I'm doing some unit tests which are executed from bash. Unit tests are initialized, executed and cleaned up in a bash script. This script usualy contains an init(), execute() and cleanup() functions. But they are not mandatory. I'd like to test if they are or are not defined.

我之前是通过 grep 和 seding 源来做到这一点的,但这似乎是错误的.有没有更优雅的方法来做到这一点?

I did this previously by greping and seding the source, but it seemed wrong. Is there a more elegant way to do this?

以下 sniplet 就像一个魅力:

The following sniplet works like a charm:

fn_exists()
{
    LC_ALL=C type $1 | grep -q 'shell function'
}

推荐答案

像这样:[[ $(type -t foo) == function ]] &&echo "Foo 存在"

内置的 type 命令会告诉你某些东西是函数、内置函数、外部命令还是未定义.

The built-in type command will tell you whether something is a function, built-in function, external command, or just not defined.

其他示例:

$ LC_ALL=C type foo
bash: type: foo: not found

$ LC_ALL=C type ls
ls is aliased to `ls --color=auto'

$ which type

$ LC_ALL=C type type
type is a shell builtin

$ LC_ALL=C type -t rvm
function

$ if [ -n "$(LC_ALL=C type -t rvm)" ] && [ "$(LC_ALL=C type -t rvm)" = function ]; then echo rvm is a function; else echo rvm is NOT a function; fi
rvm is a function

这篇关于判断函数是否存在于bash中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆