53

由于一个荒谬的问题,我有一个荒谬的问题。

通常,如果我想在 UNIX shell 中获取环境变量的内容,我可以这样做

echo ${VAR}

让我们假设,由于我的荒谬情况,这是不可能的。

如何在没有人查看命令本身(而不是输出)的情况​​下将环境变量的内容获取到标准输出,查看环境变量的值。

echo env(NAME_OF_VAR)尽管我似乎找不到它,但我可以想象解决方案类似于。该解决方案必须在 sh 中工作。

PS我不能为此编写脚本,它必须是内置的unix命令(我知道,荒谬的问题)

谢谢(对荒谬深表歉意)

4

7 回答 7

75

你可以做:

printenv VARIABLE_NAME

于 2010-03-19T13:43:58.097 回答
11

type the following command in terminal, it will display all the list of environment variables

printenv

now print the wanted variable like this:

echo $VARIABLENAME

于 2014-08-01T11:18:36.177 回答
5

Using ${!VAR_NAME} should be what you are looking for

> FOO=BAR123
> VAR_NAME=FOO
> echo ${VAR_NAME}
FOO
> echo ${!VAR_NAME}
BAR123
于 2018-03-26T17:58:29.333 回答
4

你的意思是这样的:

ENV() {
    printf 'echo $%s\n' $1 | sh
}

这适用于普通的旧 Bourne shell。

于 2010-03-19T13:40:32.503 回答
3

这个怎么样:

myVariable=$(env  | grep VARIABLE_NAME | grep -oe '[^=]*$');
于 2010-03-19T13:36:13.327 回答
2

The solution really depends on what the restrictions are why you can't use a simple $VAR. Maybe you could call a shell that doesn't have the restrictions and let this sub-shell evaluate the variable:

bash -c 'echo $VAR'
于 2010-03-19T13:56:59.190 回答
1
( set -o posix ; set ) | grep $var

search for all unix-compatible format variables been used

于 2018-02-13T04:25:39.360 回答