theoden8
theoden8

Reputation: 803

Shell : get function's body by it's name

I use zsh (sometimes bash). The thing is that I have multiple shell scripts and I've got no idea how to code a small function for printing function code by it's name (with highlighting; I use pygmentize -g). Here's a small example of what I want to get:


$ getfunc "somefunc"

# from    my_little_hacks.sh
somefunc () {
    # function code
}

Is it a clean and efficient way to do it in shell or awk without using nl and cat in the best time available for shell interpreter?

It is improbable for a function to have a word function in it's body except for when there are nested ones there. It is also next to impossible that it has a { or } legally unpaired inside the quotes.

Upvotes: 3

Views: 203

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 296019

declare -f funcname

...will retrieve the code for function funcname in both bash and zsh. Thus:

getfunc() {
  declare -f "$@" | pygmentize -l bash
}

Upvotes: 6

Related Questions