To check if a variable is set, see How do I check if a variable exists in an 'if' statement? ([ -v "Var${i}Value" ]
(ksh
/zsh
/bash
) or eval "[ -n \"\${Var${i}Value+set}\" ]"
(POSIX)).
Now, to loop over the variables whose name matches a pattern, in zsh
, you could do:
for varname in ${(Mk)parameters:#Var<->Value}; do
something with "$varname" and its value: "${(P)varname}"
done
To process them in numeric order, add the n
parameter expansion flag (change Mk
to Mkn
).
With bash
:
readarray -t list < <(compgen -v | grep -xE 'Var[[:digit:]]+Value')
for varname in "${list[@]}"; do
something with "$varname" and its value: "${!varname}"
done
Or replacing the readarray
with split+glob to avoid using an array:
IFS=$'\n' # split on newline
for varname in $(compgen -v | grep -xE 'Var[[:digit:]]+Value'); do
something with "$varname" and its value: "${!varname}"
done
To process them in numeric order and assuming your sort
is GNU sort
, pipe the output of grep
into sort -V
.