shell - Get bash function path from name -


a hitchhiker, waned time function taking complete, wishes find function located, can observe function himself editting file location. not wish print function body shell, path of script file containing function. our hitchhiker knows name of function, answer_life.

imagine has function within file universal-questions.sh, defined this, path of not known our hitchhiker:

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

another script, called hitchhiker-helper-scripts.sh, defined below. has function above source'd within (the hitchhiker doesn't understand source either, guess. play ball.):

source "/usr/bin/universal-questions.sh"  function find_life_answer_script() {     # print path of script containing `answer_life`     somecommand "answer_life" # should output path of script containing function. } 

so this, intrepid scripter, come in. can replace comment code in find_life_answer_script allows our hitchhiker find function located?

in bash operating in extended debug mode, declare -f give function name, line number, , path (as sourced):

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

like:

$ find_life_answer_script answer_life 3 ./universal-questions.sh 

running sub-shell lets set extdebug mode without affecting prior settings.


Comments