EDIT:
I realized I was mistaken about a central assumption in this post: The ${!prefix@}
syntax isn't able to get function names, but only variables. Therefore, there is no way to get ${!prefix@}
to return function names, even if they used underscores. Thus, the answer to the bolded question I have below is a definitive "No." Still, Edgar's answer below is quite helpful for those who would like to get a list of function names based on a certain prefix.
Original question
The bash parameter expansion manual gives us a way to obtain a list of all variables (NOT functions) in the current environment that begin with some prefix:
${!prefix@}
I have a bunch of functions that all start with foo-
, such as foo-setup
, foo-run
, foo-initialize
, etc. Now, I've tried and failed to get ${!foo-@}
and variations on it to return a list of functions starting with foo-
. I've tried ${!foo\-@}
, "${!foo\-@}"
, "${!foo-@}"
, bar=foo; ${!${bar}-@}
, and many other variants. I know that the hyphen -
has its own meaning in parameter expansion, so it's expected that, without some escaping or the like, it wouldn't work. But I'd also expect that Bash should have mechanisms for escaping special characters in any context, including during parameter expansion, unless ... perhaps that's not the case here?
(I've looked into the fact that, if I want cross-platform compatibility, I should stay clear of hyphenated function names. I would agree with that. But also, it is so much smoother to type functions with hyphens instead of underscores...)
So, in the spirit of inquiry, I pose the question: Is there any way to get a list of defined functions (or namerefs in general) that all start with a hyphenated prefix using native parameter expansion? Perhaps the solution is escaping the hyphen in a way I didn't know?
(If not, is there an alternative method, perhaps by getting the full list of variables, then filtering them to leave only the ones with the desired hyphenated prefix?)
declare -F | grep -o 'foo-.*'
ordeclare -F | grep 'hello-*' | cut -d ' ' -f3
(it's still faster too use compgen). – Edgar Magallon Sep 24 '22 at 03:08