1

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.

Mark Galeck
  • 6,155
  • 1
  • 28
  • 55

2 Answers2

1

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"
chepner
  • 497,756
  • 71
  • 530
  • 681
  • It's best to assign the value with `eval` to some variable before printing: `eval val=\$$FOOBAR; echo "$val"`. In your case the argument is not quoted. Also, I was thinking about `FOOBAR=$(echo "$FOOBAR" | tr -dc [:alnum:]_); eval val=\$$FOOBAR`. Or `[ "$FOOBAR" != "$(echo "$FOOBAR" | tr -dc [:alnum:]_)" ] && eval ...` (or terminate the script right away). But your solution is a bit better (always start with alpha). – x-yuri Jun 29 '22 at 13:44
1

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318