Shell – Globbing shell variable names

shellvariable

I need to expand some shell (not environment) variable names that are thematically related, e.g. B2_... where ... could be one or more different things like ACCOUNT_ID, ACCOUNT_KEY, RESPOSITORY and so on.

I don't know ahead how many variables there are nor which ones they are. That is what I'm want to find out.

I want to be able to iterate through the B2... variables without having to put each individual name in the list, similar to how I would glob filename expansions.

I use zsh for interactive sessions, but solutions for sh or bash are good too.

Best Answer

Using parameter expansion :

$ foobar_1=x foobar_2=y foobar_3=z
$ for v in "${!foobar_@}"; do echo "$v"; done

Output :

foobar_1
foobar_2
foobar_3

'dereference' :

$ for v in "${!foobar_@}"; do echo "${!v}"; done

Output² :

x
y
z
Related Question