参见英文答案 >
How do I list the functions defined in my shell?6个
我有一个Bourne Shell脚本,其中包含多个函数,并允许以下列方式调用:
我有一个Bourne Shell脚本,其中包含多个函数,并允许以下列方式调用:
my.sh< func_name> <参数1> < param2的>
将使用param1和param2调用func_name()内部.
我想创建一个“帮助”功能,只列出所有可用的功能,即使没有参数.
我想避免解析它并寻找功能模式.太容易出错了.
谢谢,
亚历克斯
更新:代码.想要我的help()函数就像main() – 添加到代码中的函数会自动添加到帮助中.
- #!/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可以找到它们.这是一个示例:
- $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
如果你有“私人”功能,你不想在帮助中显示,那么省略“功能”部分:
- my_private_function()
- {
- # Do something
- }