在Shell脚本中获取函数名称列表 [英] Get a list of function names in a shell script
问题描述
我有一个Bourne Shell脚本,其中包含多个功能,并且可以通过以下方式调用:
I have a Bourne Shell script that has several functions in it, and allows to be called in the following way:
my.sh <func_name> <param1> <param2>
在内部,将用param1
和param2
调用func_name()
.
我想创建一个help
函数,该函数将仅列出所有可用函数,即使没有参数也是如此.
I want to create a help
function that would just list all available functions, even without parameters.
问题:如何从脚本内部获取脚本中所有函数名称的列表?
The question: how do I get a list of all function names in a script from inside the script?
我想避免不得不解析它并寻找功能模式.太容易出错.
I'd like to avoid having to parse it and look for function patterns. Too easy to get wrong.
更新:代码.希望我的help()
函数像main()
一样-添加到代码中的函数会自动添加到帮助中.
Update: the code. Wanted my help()
function be like main()
- a function added to the code is added to the help automatically.
#!/bin/sh
# must work with "set -e"
foo ()
{
echo foo: -$1-$2-$3-
return 0
}
# only runs if there are parameters
# exits
main ()
{
local cmd="$1"
shift
local rc=0
$cmd "$@" || rc=$?
exit $rc
}
if [[ "$*" ]]
then
main "$@"
die "how did we get here?"
fi
推荐答案
您可以通过在自己的脚本上使用grep命令来获取脚本中的功能列表.为了使这种方法起作用,您将需要以某种方式构造函数,以便grep可以找到它们.这是一个示例:
You can get a list of functions in your script by using the grep command on your own script. In order for this approach to work, you will need to structure your functions a certain way so grep can find them. Here is a sample:
$ cat my.sh
#!/bin/sh
function func1() # Short description
{
echo func1 parameters: $1 $2
}
function func2() # Short description
{
echo func2 parameters: $1 $2
}
function help() # Show a list of functions
{
grep "^function" $0
}
if [ "_$1" = "_" ]; then
help
else
"$@"
fi
这是一个交互式演示:
$ my.sh
function func1() # Short description
function func2() # Short description
function help() # Show a list of functions
$ my.sh help
function func1() # Short description
function func2() # Short description
function help() # Show a list of functions
$ my.sh func1 a b
func1 parameters: a b
$ my.sh func2 x y
func2 parameters: x y
如果您不想在帮助中显示私人"功能,请省略功能"部分:
If you have "private" function that you don't want to show up in the help, then omit the "function" part:
my_private_function()
{
# Do something
}
这篇关于在Shell脚本中获取函数名称列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!