0

I have this:

cd 31 /Users/alexamil/WebstormProjects/oresoftware/botch/botch-shell-overrides.sh

the above style output, is given by this command:

declare -F my_bash_func

How can I grab just the file name from that result? something like:

file=$(declare -F my_bash_func | grab_3rd_entry)

I have to use:

shopt -s extdebug
declare -F my_bash_func
shopt -u extdebug

but this doesn't work on MacOS:

shopt -s extdebug
declare -pf my_bash_func
shopt -u extdebug

the latter yields a weird error:

declare: my_bash_func: not found

but using declare -F can find the function, so not sure why the -pf option doesn't work.

Alexander Mills
  • 9,330
  • 19
  • 95
  • 180

1 Answers1

0

You can use awk for that:

file=$(declare -F my_bash_func | awk '{print $3}')

Or use bash built-ins, read it into an array:

func_info=( $(declare -F my_bash_func) )
file=${func_info[2]}
line_number=${func_info[1]}

But beware that declare -F my_bash_func output is not very friendly to parsers... If the file containing the function is sourced from a relative path, the extdebug output will just print a relative path (even if you're not in that directory anymore.) Furthermore, if the path has any spaces or unprintable characters, those will be preserved in the output (so "3rd field" is maybe not correct...)

filbranden
  • 21,113
  • 3
  • 58
  • 84