I have the need to list all functions in Bash, because I want to have a lazy way to invoke those functions without specifically listing by hand.
Say you have these two dummies:
func1() { :;} func2() { :;}
1 declare or typeset
declare and typeset are synonyms to each other in Bash. If you use with declare -f, you will get
func1 () { : } func2 () { : }
From bash(1):
The -f option will restrict the display to shell functions.
Initially, without argument, declare lists all variables and functions with their values and definition. -f instructs to only function, but the definitions are still listed, which are the parts we don’t need and don’t want to have. There is another option -F:
The -F option inhibits the display of function definitions; only the function name and attributes are printed.
With declare -F:
declare -f func1 declare -f func2
Therefore you would do something like the following to extract the function name part:
declare -F | cut -d ' ' -f 3
And you will get the only function names:
func1 func2
2 set
From bash(1):
Without options, the name and value of each shell variable are displayed in a format that can be reused as input for setting or resetting the currently-set variables.
I don’t like this method—though it’s similar to declare without arguments—because the output is mixed with variables. But if you want you can use:
set | sed -n '/[^ ]\+\ ()/ s/ ()//p'
3 compgen
From bash(1):
-A action
- function
- Names of shell functions.
It really looks strange to use completion related functionality to list function names, but it does the job the most elegant way:
compgen -A function
No extraction is needed.
4 Usage of the function names
Whatever you choose to get the function names, the next step is to use it, that is calling them. For my case, I would do like:
funcs=($(compgen -A function)) for f in funcs; do # do some filter if the list is mixed with some other functions, you may # want to pseudo namespace'd functions you want to invoke. $f "$arg1" "$arg2" "..." done
The list may contain functions you don’t need, so you probably need to check the names before calling them.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.