How to create a dynamic variable and assign value to it?

You can use bash’s declare directive and indirection feature like this:

p_val="foo"
active_id=$p_val
declare "flag_$active_id"="100"

TESTING:

> set | grep flag
flag_foo=100

UPDATE:

p_val="foo"
active_id="$p_val"
v="flag_$active_id"
declare "$v"="100"

> echo "$v"
flag_foo
> echo "${!v}"
100

Usage in if condition:

if [ "${!v}" -ne 100 ]; then
   echo "yes"
else
   echo "no"
fi

# prints no

Leave a Comment