Globbing shell variable names

Using bash 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

Instead of using individual variables with names beginning with B2_, you could use an associative array (B2). e.g.

Note: the following is specific to zsh. ksh and bash also have associative arrays, but the syntax for initialising and using them is different (see below).

typeset -A B2
# initialise array
B2=(ACCOUNT_ID 12345 ACCOUNT_KEY 54321 REPOSITORY somewhere)

# two different ways of adding elements to the array
B2[FOO]=bar
B2+=(NAME fred)             

for key val in ${(kv)B2}; do 
  echo "$key: $val"
done

Output for that example would be:

ACCOUNT_KEY: 54321
FOO: bar
REPOSITORY: somewhere
ACCOUNT_ID: 12345
NAME: fred

You can also print the entire array (in a form suitable for re-use in a script or on the command line) with typeset -p:

% typeset -p B2
typeset -A B2=( ACCOUNT_ID 12345 ACCOUNT_KEY 54321 FOO bar NAME fred REPOSITORY somewhere )

The same operations in ksh or Bash would be as follows:

# initialise it
typeset -A B2
B2=([ACCOUNT_ID]=12345 [ACCOUNT_KEY]=54321 [REPOSITORY]=somewhere)

# add elements
B2[FOO]=bar
B2+=([NAME]=fred) 

# get a list of the keys and use them as indexes to get the values
for key in "${!B2[@]}"; do 
  echo "$key: ${B2[$key]}"
done

# print the entire array
typeset -p B2

Bash has compgen -v.

In Bash, you can list variable names that begin with B2 using:

compgen -v B2

Running the command compgen -v text lists the same variables that are available as autocompletion results when you type $ followed by text and then press tab. (You may have to press tab multiple times for them all to be displayed.) You can use compgen -v interactively, but you can also use it in a script. For example:

$ bash -c 'compgen -v SDK'
SDKMAN_CANDIDATES_DIR
SDKMAN_CURRENT_API
SDKMAN_DIR
SDKMAN_LEGACY_API
SDKMAN_PLATFORM
SDKMAN_VERSION

(The script can, of course, be in a file, rather than passed to bash as an operand to the -c flag.)

The purpose of compgen is to perform command completions. See the output of help compgen (in Bash) for general information about it. Although this will probably do what you want, you might find that other approaches, such as the parameter expansion technique in Gilles Quenot's answer, more clearly express what you're doing. I can't really say which is better, as this depends on what you are doing and perhaps also on your personal stylistic preferences.

Tags:

Shell

Variable