On Tue, 27 Jun 2023 18:37:37 +0200 Fabien Orjollet <of1+bugb...@disroot.org> wrote:
> I'm far from having the skills of the people here. However, I found the > problem interesting. I think I've come up with a reasonable solution > (you tell me). Although it's not as short as Kerin Millar's, I think it > offers some improvements. I hope there are no particular weaknesses. > If it's of any use to anyone. > > > declare-P() { > local curVar > declare -a curVars > > readarray -t curVars <<<"$1" > curVars=( "${curVars[@]%%=*}" ) > curVars=( "${curVars[@]##* }" ) > > for curVar in "${curVars[@]}"; do > ### unfortunately, we cannot use [[ -v "$curVar" ]] > [[ "${curVar//[a-zA-Z0-9_]}" || \ > "${curVar:0:1}" == [0-9] || \ > ! "$curVar" =~ $2 ]] || printf '%s\n' "$curVar" > done > } > > declare-P "$(declare -p)" > echo "##################" > declare-P "$(declare -p)" "TERM" > echo "##################" > declare-P "$(declare -p)" "^BASH|^SHELL" > It doesn't work at all for >=5.2. The reason for this is interesting and I may make a separate post about it. Prior to 5.2, it can easily be tricked into printing names that do not exist. $ VAR=$'\nNONEXISTENT=' ./declare-P | grep ^NONEXISTENT NONEXISTENT All of this lends further credence to Eli's post. Parsing declare -F is a minor nuisance, whereas parsing declare -p is broken by design. While the format of declare -p improved for 5.2, there is no guarantee of forward-compatibility. -- Kerin Millar