bash 从另一个字符串的值创建字符串变量名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13716607/
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
Creating a string variable name from the value of another string
提问by NeonGlow
In my bash script I have two variables CONFIG_OPTION
and CONFIG_VALUE
which contain string VENDOR_NAME
and Default_Vendor
respectively.
在我的 bash 脚本中,我有两个变量CONFIG_OPTION
,CONFIG_VALUE
分别包含字符串VENDOR_NAME
和Default_Vendor
。
I need to create a variable with name $CONFIG_OPTION
ie VENDOR_NAME
and assign the value in CONFIG_VALUE
to newly created variable.
我需要创建一个名称为$CONFIG_OPTION
ie的变量VENDOR_NAME
并将值分配CONFIG_VALUE
给新创建的变量。
How I can do this?
我怎么能做到这一点?
I tried
我试过
$CONFIG_OPTION=$CONFIG_VALUE
But I am getting an error on this line as
但是我在这条线上收到了一个错误
'./Build.bash: line 137: VENDOR_NAME="Default_Vendor": command not found'
Thanks.
谢谢。
回答by gniourf_gniourf
I know that nobody will mention it, so here I go. You can use printf
!
我知道没有人会提到它,所以我走了。你可以用printf
!
#!/bin/bash
CONFIG_OPTION="VENDOR_NAME"
CONFIG_VALUE="Default_Vendor"
printf -v $CONFIG_OPTION "$CONFIG_VALUE"
# Don't believe me?
echo "$VENDOR_NAME"
Done!
完毕!
Incidentally, it's a rather fast method (just as fast as the declare
method).
顺便说一句,这是一种相当快的方法(与declare
方法一样快)。
回答by Kousha
This uses bash builtins:
这使用 bash 内置函数:
#!/bin/bash
VAR1="VAR2"
declare "${VAR1}"="value"
echo "VAR1=${VAR1}"
echo "VAR2=${VAR2}"
The script output:
脚本输出:
VAR1=VAR2
VAR2=value
Here's the snippet using your variable names:
这是使用您的变量名称的代码段:
#!/bin/bash
CONFIG_OPTION="VENDOR_NAME"
declare "${CONFIG_OPTION}"="value"
echo "CONFIG_OPTION=${CONFIG_OPTION}"
echo "VENDOR_NAME=${VENDOR_NAME}"
The script output:
脚本输出:
CONFIG_OPTION=VENDOR_NAME
VENDOR_NAME=value
回答by Leonard Pauli
For pure shell, possibly try:
对于纯外壳,可能尝试:
#!/usr/bin/env sh
option=vendor_name
value="my vendor"
eval $option="'$value'" # be careful with ', \n, and \ in value
eval echo "$$option" # my vendor
echo "$vendor_name" # my vendor
Why?
为什么?
#!/usr/bin/env sh
printf -v "var" "val" # prints the flag, var not set
declare var=val # sh: declare: not found
echo ${!var} # sh: syntax error: bad substitution
I don't like eval, but are there any POSIX options?
我不喜欢 eval,但是有没有 POSIX 选项?