How to retreive value from using variable-numbers-name

Hello.
I can initialize variable-numbers-name in a for loop like :

CHECKBOX_UNCHECK="□"
LIMIT=255

for ((i = 0 ; i <= LIMIT ; i++)); do
  echo "Counter: $i"
  eval "STATUS$i=$CHECKBOX_UNCHECK"
  echo "STATUS$i : $STATUS$i"
done

Now I would like to read the value of a variable :

I can do it like this

i=10
A_VALUE=$( eval "echo \$$!STATUS${i}")

Is there another way to do it without using eval ?

Any help or comment is welcome.

Ever thought about using an array for this?

BTW, the section is “Programming/Scripting”, but you then should specify the language and not let others guess.

It depends on the shell you use.

In the assumption that you’re using bash

declare “STATUS$i=$CHECKBOX_UNCHECK”

Have you actually tried it yourself?

Sure, I did, unfortunately I did not saw the eval in the assignment , thats on me.

An associative array is an alternative, something like

declare -A dynamic_vars  # Declare an associative array
i=10
 pid=$$
 varname="STATUS${i}"  # Construct the variable part

# Store the value in an associative array using pid as part of the key
dynamic_vars["${pid}_${varname}"]="some_value" 
# # Access the value
# A_VALUE=${dynamic_vars["${pid}_${varname}"]}
# echo "A_VALUE: $A_VALUE"

for i in "${!dynamic_vars[@]}"; do
  printf '%s %s\n' "$i" "${dynamic_vars[$i]}"
done

My advise would be, chose another programming language. One with a debugger and one where you do not need eval.

1 Like

Thank you very much

global variable STATUS25 is set somewhere.

z=25
TEMP_VAR=“STATUS$z”
CUR_VALUE=${!TEMP_VAR}

CUR_VALUE got the value of STATUS25

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.