Bash – How to find the file where a bash function is defined

bash

I cannot figure out how to find the file where a bash function is defined (__git_ps1 in my case).

I experimented with declare, type, which, but nothing tells me the source file. I read somewhere that declare can print the file name and the line number, but it was not explained how. The help page for declare does not say it either.

How can I get this information?

Best Answer

If you are prepared to run the function, then you can get the information by using set -x to trace the execution and setting the PS4 variable.

  1. Start bash with --debugger or else use shopt -s extdebug to record extra debugging info.

  2. Set PS4, the 'prompt' printed when tracing to show the source line.

  3. Turn on tracing.

  4. you can then run your function and for each line you will get the filename of the function.

  5. use set +x to turn off tracing.

So for this case you would run

bash --debugger
PS4='+ ${BASH_SOURCE[0]} '
set -x ; __git_ps1 ; set +x