14

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 ?

1

2 Answers 2

24

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
Sign up to request clarification or add additional context in comments.

5 Comments

thanks anubhava, but i am getting error in this code: if [ flag_$active_id -ne 100 ] then ... else ...
@ShivamAgrawal: Check my Update section, I have provided an example of its use in if then ... else ... fi block.
what is the significance of semicolon here "if [ "${!v}" -ne 100 ];"
"${!v}" is called indirection which means the real variable name is contained in $v (flag_foo)
this does not work for assigning an array. solution is here: stackoverflow.com/a/16487405/3779853
5

I don't know what this should be good for but you can achieve stuff like this with bash's eval statement.

The following code illustrates that.

#!/bin/bash

p_val="TEST"
active_id=$p_val 

eval "flag_$active_id=100"

echo $flag_TEST
eval "echo \$flag_$active_id"

The terminating echo's puts

100
100

on the stdout.

1 Comment

Just a friendly word of warning, while this will work, eval is a super dangerous, specially on the shell. so never use in anything that comes from user input. ever.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.