Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Examine Bash variables with dynamic names

I'm trying to read from Bash variables for which I know name suffixes, but I want to iterate through the prefixes.

I give an example below:

var1_name="variable1"
var1_size="2"
var2_name="variable2"
var2_size="3"
vars=(var1 var2)

for v in "${vars[@]}"
do
    echo $v_name
    echo $v_size
done

and I'd want the output to look like follows:

variable1
2
variable2
3

Is there any to do this with Bash? I have tried with eval and associative arrays, but I still can't find a way to examine an already defined variable.

like image 306
Ofri Rips Avatar asked Feb 15 '26 06:02

Ofri Rips


1 Answers

Below works for me. You need to construct the variable first and then evaluate it using exclamation.

var1_name="variable1"
var1_size="2"
var2_name="variable2"
var2_size="3"
vars=("var1" "var2")

for v in "${vars[@]}"
do
    name=${v}_name
    size=${v}_size
    echo ${!name}
    echo ${!size}
done

O/P

variable1
2
variable2
3
like image 72
auhuman Avatar answered Feb 16 '26 20:02

auhuman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!