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"