Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh equivalent of bash ${!name*} or ${!name@}

Tags:

zsh

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

like image 415
chepner Avatar asked Nov 23 '19 14:11

chepner


1 Answers

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 option TYPESET_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
like image 98
hchbaw Avatar answered Nov 18 '22 05:11

hchbaw