I am trying to create a dynamic variable and assign 100
to it
#!/bin/bash
.
.
active_id=$p_val
flag_$active_id=100
But I am getting error in doing so, any help ?
Use the for Loop to Create a Dynamic Variable Name in Python The globals() method in Python provides the output as a dictionary of the current global symbol table. The following code uses the for loop and the globals() method to create a dynamic variable name in Python. Output: Copy Hello from variable number 5!
There are no dynamic variables in Java. Java variables have to be declared in the source code1. Depending on what you are trying to achieve, you should use an array, a List or a Map ; e.g. It is possible to use reflection to dynamically refer to variables that have been declared in the source code.
Inside eval(), we pass a string in which variable valuei is declared and assigned a value of i for each iteration. The eval() function executes this and creates the variable with the assigned values. The code is given below implements the creation of dynamic variable names using eval().
In programming, a dynamic variable is a variable whose address is determined when the program is run. In contrast, a static variable has memory reserved for it at compilation time.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With