bash 如何创建动态变量并为其赋值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18018808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:07:07  来源:igfitidea点击:

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

linuxbashshell

提问by Shivam Agrawal

I am trying to create a dynamic variable and assign 100to it

我正在尝试创建一个动态变量并分配100给它

#!/bin/bash
.
.   
active_id=$p_val 
flag_$active_id=100

But I am getting error in doing so, any help ?

但是我这样做时出错了,有什么帮助吗?

回答by anubhava

You can use bash's declare directive and indirection featurelike this:

您可以像这样使用bash 的声明指令和间接功能

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 condition

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

# prints no

回答by user1146332

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

我不知道这有什么好处,但你可以用 bash 的eval语句来实现这样的东西。

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

终止echo的看跌期权

100
100

on the stdout.

stdout.