How would one get a list of functions in a shell script?

555 Views Asked by At

I want to generate a list of all functions in a shell script (a shell script function library that I am sourcing). Currently, I am experimenting with typeset in ways such as the following:

typeset -f
typeset -F
typeset -F | awk -F"declare -f " '{print $2}' | grep -v '_'

A difficulty I am having is that some functions which are not in the function library are listed and I don't know how to excise these from the function listing or how to generate the function listing in a better way. I would welcome any ideas you may have on this.

A bonus would be to generate a function listing in the order in which the functions appear in the shell script.

2

There are 2 best solutions below

1
mr.spuratic On BEST ANSWER

I assume bash is the shell. typeset (or declare ) show the current environment, functions are part of the environment:

  • there's no inherent ordering in the environment (names are sorted on output)
  • the unwanted functions may be inherited from the environment, having been previously been marked for export with declare -x

You could experiment with "env" to start your script in a clean environment, try:

env -i "PATH=$PATH" "TERM=$TERM" "LANG=$LANG" myscript.sh

as starting point.

The best way to enumerate functions in bash is documented here: Where is function's declaration in bash? Note that "declare -F" does not normalise the filename, it will be as invoked/sourced.

while read xx yy fn; do
    func=( $(shopt -s extdebug; declare -F $fn) )
    printf  "%-30s %4i %-30s\n" "${func[@]:2}" "${func[1]}" "${func[0]}"
done < <(declare -F)

All you need to do is filter by the required filename, and sort by line number.

0
d3pd On

One approach I have is as follows (where the code is contained in the function library script):

initialListOfFunctionsInEnvironment="$(typeset -F | awk -F"declare -f " '{print $2}')"
# declare functions
finalListOfFunctionsInEnvironment="$(typeset -F | awk -F"declare -f " '{print $2}')"
diff  <(echo "${initialListOfFunctionsInEnvironment}" ) <(echo "${finalListOfFunctionsInEnvironment}") | grep -E '^(<|>)' | awk -F"> " '{print $2}'

This seems to produce a simple list of all functions that are added to the environment when the function library script is sourced. Criticism of this approach would be appreciated.