Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing defined functions in Bash

I'm trying to write some code in bash which uses introspection to select the appropriate function to call.

Determining the candidates requires knowing which functions are defined. It's easy to list defined variables in bash using only parameter expansion:

$ prefix_foo="one"
$ prefix_bar="two"
$ echo "${!prefix_*}"
prefix_bar prefix_foo

However, doing this for functions appears to require filtering the output of set -- a much more haphazard approach.

Is there a Right Way?

like image 508
Charles Duffy Avatar asked Apr 12 '10 22:04

Charles Duffy


People also ask

Where are functions stored in bash?

Typically bash functions are permanently stored in a bash start-up script. System-wide start-up scripts: /etc/profile for login shells, and /etc/bashrc for interactive shells.

Which command can be used to list all functions present in your bash shell?

The -F option to declare will list the function names only (and optionally the source file and line number).

Can you define functions in bash?

Defining Bash FunctionsFunctions may be declared in two different formats: The first format starts with the function name, followed by parentheses. This is the preferred and more used format. The second format starts with the reserved word function , followed by the function name.


2 Answers

How about compgen:

compgen -A function   # compgen is a shell builtin
like image 96
trevvor Avatar answered Oct 06 '22 22:10

trevvor


$ declare -F
declare -f ::
declare -f _get_longopts
declare -f _longopts_func
declare -f _onexit
...

So, Jed Daniel's alias,

declare -F | cut -d" " -f3

cuts on a space and echos the 3rd field:

$ declare -F | cut -d" " -f3
::
_get_longopts
_longopts_func
_onexit
like image 24
Kevin Little Avatar answered Oct 06 '22 22:10

Kevin Little