我正在尝试将“嵌套”变量的值获取到另一个变量中和/或直接使用该值,如下所示
下面是一个示例场景,它准确地解释了我被困在哪里
$ USER1_DIR=./user1/stuff
$ USER2_DIR=./user2/stuff
$ USER3_DIR=./user3/stuff
#User will be taken as input, for now assuming user is USER1
$ USER="USER1"
$ DIR=${USER}_DIR
$ echo $DIR
>> USER1_DIR
$ DIR=${${USER}_DIR}
>> -bash: ${${USER}_DIR}: bad substitution
Challenge 1:
Get DIR value to ./user1/stuff when the input is USER1
or
Get ./user1/stuff as output when the input is USER1
在我能够通过挑战 1 之后,我必须向用户目录中的文件添加一些内容,如下所示
Desired output is as below
$ echo "Some stuff of user1" >> $DIR/${DOC}$NO
# Lets say DOC="DOC1" and NO="-346"
# So the content has to be added to ./user1/stuff/DOC1-346
# Assume that all Directories exists
仅供引用,以上代码将成为 bash 脚本中函数的一部分,并且将仅在 Linux 服务器上执行。
注意:我不知道如何称呼变量 DIR,因此使用术语“嵌套”变量。很高兴知道它叫什么,非常感谢任何见解。 :)
您可以使用eval
、变量间接 ${!...}
,或引用变量 声明-n
。
在下文中,我将使用小写变量名,因为按照惯例大写变量名是特殊的。尤其是覆盖 $USER
是不好的,因为该变量通常包含您的用户名(没有明确设置)。对于以下代码片段,假定以下变量:
user1_dir=./user1/stuff
user=user1
评估
eval "echo \${${user}_dir}"
# prints `./user1/stuff`
Eval 是一个内置的 bash,它执行它的参数,就好像它们是在 bash 本身中输入的一样。此处,使用参数 echo "${user1_dir}"
调用 eval
。
使用 eval
被认为是不好的做法,参见 this question .
变量间接寻址
当将变量var1
的名称存储在另一个变量var2
中时,可以使用间接寻址${!var2}
来获取值var1
.
userdir="${user}_dir"
echo "${!userdir}"
# prints `./user1/stuff`
引用变量
除了每次都使用间接寻址之外,您还可以在 bash 中声明一个引用变量:
declare -n myref="${user}_dir"
引用的使用类似于变量间接寻址,但无需编写 !
。
echo "$myref"
# prints `./user1/stuff`
备选方案
使用(关联)数组时,您的脚本可能会变得更容易。数组是存储多个值的变量。可以使用索引访问单个值。普通数组使用自然数作为索引。关联数组使用任意字符串作为索引。
(普通)数组
# Create an array with three entries
myarray=(./user1/stuff ./user2/stuff ./user3/stuff)
# Get the first entry
echo "${myarray[0]}"
# Get the *n*-th entry
n=2
echo "${myarray[$n]}"
关联数组
声明一个包含三个条目的关联数组
# Create an associative array with three entries
declare -A myarray
myarray[user1]=./user1/stuff
myarray[user2]=./user2/stuff
myarray[user3]=./user3/stuff
# Get a fixed entry
echo "${myarray[user1]}"
# Get a variable entry
user=user1
echo "${myarray[$user]}"