[英]How to check if function was not called in shell script
我有以下脚本,在其中我从“ lib”文件调用函数。 工作正常。 但是如何实现异常处理,以便如果我在脚本文件或“ lib”文件中更改函数名称而未调用函数,则应终止脚本。
脚本文件:
#!/bin/bash
#Include Functions file
. ./testlibrary.lib
echo "Start"
testFunction
echo "Finish"
LibraryFile:
#!/bin/bash
testFunction(){
echo "testing begins"
echo "testing ends"
}
注意:
我不能使用“ set -e”标志,所以还有其他方法可以实现该功能:如果我的命令失败,则应终止脚本。
您可以预先查看该函数是否具有typeset
:
if [[ -z "$(typeset -f testFunction)" ]] ; then
echo Cannot find testFunction
exit
fi
testFunction
有点麻烦,但到目前为止我的最低测试似乎还可以。 但是,您可能需要注意一些极端情况。
您可以使用:
if ! testFunction
then echo "testFunction not found"
exit
fi
只要函数本身永远不会因错误而退出。
您通常可以检查函数调用是否失败,如下所示:
testFunction || exit 1
注意,这不能区分“找不到功能”和“功能失败”。 如果需要这样做,请在调用函数之前执行以下操作:
type -t testFunction >/dev/null || exit 1
testFunction # definitely exists, could still fail but we'll ignore that
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.