How to create a dynamic variable and assign value

2020-01-29 07:50发布

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 ?

标签: linux bash shell
2条回答
三岁会撩人
2楼-- · 2020-01-29 08:05

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
查看更多
家丑人穷心不美
3楼-- · 2020-01-29 08:14

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.

查看更多
登录 后发表回答