Nick Bull Nick Bull - 3 months ago 8x
Bash Question

Get bash function path from name

A hitchhiker, waned by the time a function is taking to complete, wishes to find where a function is located, so that he can observe the function for himself by editting the file location. He does not wish to print the function body to the shell, simply get the path of the script file containing the function. Our hitchhiker only knows the name of his function, which is


Imagine he has a function within a file
, defined like this, the path of which is not known to our hitchhiker:

function answer_life() {
sleep $(date --date='7500000 years' +%s)

echo "42"

Another script, called
, is defined below. It has the function above
'd within it (the hitchhiker doesn't understand
either, I guess. Just play ball.):

source "/usr/bin/"

function find_life_answer_script() {
# Print the path of the script containing `answer_life`
somecommand "answer_life" # Should output the path of the script containing the function.

So this, my intrepid scripter, is where you come in. Can you replace the comment with code in
that allows our hitchhiker to find where the function is located?


In bash operating in extended debug mode, declare -F will give you the function name, line number, and path (as sourced):

function find_life_answer_script() {
    ( shopt -s extdebug; declare -F answer_life )


$ find_life_answer_script
answer_life 3 ./

Running a sub-shell lets you set extdebug mode without affecting any prior settings.