使用其他变量的聚合值获取变量的值[重复]

时间:2022-08-06 12:59:42

This question already has an answer here:

这个问题在这里已有答案:

Given:

export A='TEST_'
export B='VAR'

How would I get the value of $TEST_VAR in this case?

在这种情况下,如何获得$ TEST_VAR的值?

Some more conditions:

更多条件:

  • should work both on sh and bash of the latest versions.
  • 应该适用于最新版本的sh和bash。

  • should not use any not pre-installed ubuntu dependencies.
  • 不应该使用任何未预先安装的ubuntu依赖项。

  • should be the simplest one liner solution
  • 应该是最简单的单线解决方案

1 个解决方案

#1


You can use indirect variable reference:

您可以使用间接变量引用:

test_var='foo bar baz'
a='test_'
b='var'
c="${a}${b}"

echo "${c}"
test_var

echo "${!c}"
foo bar baz

PS: You should avoid all uppercase variables in Unix to avoid collision with shell internal variables.

PS:你应该避免使用Unix中的所有大写变量来避免与shell内部变量冲突。

#1


You can use indirect variable reference:

您可以使用间接变量引用:

test_var='foo bar baz'
a='test_'
b='var'
c="${a}${b}"

echo "${c}"
test_var

echo "${!c}"
foo bar baz

PS: You should avoid all uppercase variables in Unix to avoid collision with shell internal variables.

PS:你应该避免使用Unix中的所有大写变量来避免与shell内部变量冲突。