Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

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 ?

like image 493
Shivam Agrawal Avatar asked Aug 02 '13 14:08

Shivam Agrawal


People also ask

How do you assign a value to a dynamic variable in Python?

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!

How do you assign a dynamic value to a variable in Java?

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.

How do you create a dynamic variable name?

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().

What is a dynamic variable?

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.


1 Answers

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
like image 63
anubhava Avatar answered Oct 16 '22 18:10

anubhava