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.

  • could you provide the output of declare -pf my_bash_func ? – Isaac May 2 '18 at 5:17
  • I am on MacOS, has to be x-platform :( – Alexander Mills May 2 '18 at 5:19
  • I added details to answer your question – Alexander Mills May 2 '18 at 5:21
  • Ok, make that declare -f my_bash_func which works for bash (as you tagged your question) since version 2.03. – Isaac May 2 '18 at 5:24

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) )

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...)


Since it is bash, you can do:

< <(shopt -s extdebug; declare -F my_bash_func) IFS=' ' read -d '' _ _ fn
echo "$fn"

That will reset the value of extdebug on exiting the subshell.
This will work with files with spaces and newlines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.