In bash
, there is a parameter expansion to generate the names of variables matching a given prefix. For example:
$ foo1=a foo2=b four=4
$ echo "${!foo@}"
foo1 foo2
Is there an equivalent in zsh
? I know the (P)
parameter expansion flag is the equivalent of the similar bash
indirection expansion ${!foo}
:
# bash
$ foo=bar bar=3
$ echo ${!foo}
3
# zsh
% foo=bar bar=3
% echo ${(P)foo}
3
but as far as I can tell, (P)
does not also handle prefix matching.
% echo "${(P}foo@}"
zsh: bad substitution
There doesn't seem to be any way to perform any type of globbing on a parameter name, only on the expansion of a parameter.
(This seems to be a necessary precursor for a solution for "Use wildcard expansion to echo all variables in zsh", though I could be mistaken about that.)
typeset -m
could rescue:
-m
If the
-m
flag is given the name arguments are taken as patterns (use quoting to prevent these from being interpreted as file patterns). With no attribute flags, all parameters (or functions with the-f
flag) with matching names are printed (the shell optionTYPESET_SILENT
is not used in this case).-- zshbuiltins(1), shell builtin commands, typeset
% foo1=a foo2=b four=4
% typeset -m 'foo*'
foo1=a
foo2=b
% typeset +m 'foo*'
foo1
foo2
% setopt extendedglob
% print -l ${$(typeset +m 'foo*')/(#m)*/${(P)MATCH}}
a
b
Or $parameters
from zsh/parameters
module could help:
parameters
The keys in this associative array are the names of the parameters currently defined.
-- zshmodules(1), the zsh/parameter module, parameters
% foo1=a foo2=b four=4
% print -l ${(Mk)parameters:#foo*}
foo1
foo2
% setopt extendedglob
% print -l ${${(Mk)parameters:#foo*}/(#m)*/${(P)MATCH}}
a
b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With