linux - Bash - 将 'nested' 变量的值获取到另一个变量中 [编辑 : Indirect Variable Expansion]

标签 linux bash sh

我正在尝试将“嵌套”变量的值获取到另一个变量中和/或直接使用该值,如下所示

下面是一个示例场景,它准确地解释了我被困在哪里

$ 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]}"

关于linux - Bash - 将 'nested' 变量的值获取到另一个变量中 [编辑 : Indirect Variable Expansion],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46383243/

相关文章:

c - 查找进程 linux(C 代码)的打开文件描述符?

linux - 在 Linux 中显示包含某些字符的整行

bash - 替换 yaml 文件中的行

bash:评论一个长管道

sh - 在 Vala 中执行外部命令不会返回所需的数据

linux - 通过 bash 命令注释以查看 pkill

linux - 在 bash 中使用 Whiptail 在图形界面中显示日志的充分方法

linux - ssh并执行命令而不退出

macos - 如何摆脱 Mac OS X 中 ps 命令中的 header ?

unix - 如何在 Unix 中找到减去 7 天的当前日期?