Mark Galeck
Mark Galeck

Reputation: 6385

in POSIX shell, how to print the value of the value of a variable

In a POSIX shell:

>VALUE=value
>FOOBAR=VALUE

Now how to print the value of $FOOBAR? $$FOOBAR does not work - it goes left-to-right so interprets $$ first as process ID.

The duplicate question before me that people are pointing to, yes it does contain the answer to my question but it buried in a ton of irrelevant gunk. My question is much simpler and to the point.

Upvotes: 1

Views: 798

Answers (2)

tripleee
tripleee

Reputation: 189357

For POSIX portability, you are pretty much left with

eval echo \$$variable

The usual caveats apply; don't use eval if the string you pass in is not completely and exclusively under your own control.

I lowercased your example; you should not be using upper case for your private variables, as uppercase names are reserved for system use.

Upvotes: 1

chepner
chepner

Reputation: 531055

The only way to do this in POSIX is to use eval, so be very certain that FOOBAR contains nothing more than a valid variable name.

$ VALUE=value
$ FOOBAR=VALUE
$ valid_var='[[:alpha:]_][[:alnum:]_]*$'
$ expr "$FOOBAR" : "$valid_var" > /dev/null && eval "echo \$$FOOBAR"

Upvotes: 1

Related Questions