2

i am trying to read the value of a bash variable defined earlier , but this variable name derived dynamically.

this is the bash script i am trying to do

  $ mythreshold=10
  $ table=my
  $ threshold="$table"threshold
  $ echo $("$threshold")
   mythreshold

but when i try to read this variable value like

    $ echo $("$threshold")
    -bash: mythreshold: command not found

however i was expecting it to print

  $ echo $("$threshold")
   10

is there a way i can get this work, it should have printed the value of mythreshold variable defined above

dpsdce
  • 5,290
  • 9
  • 45
  • 58

2 Answers2

6

$() is Command Substitution. It runs the command inside and returns the output. A variable name is not a command.

You can $(echo "$threshold") but that will only get the mythreshold back.

You need indirection for what you want. Specifically Evaluating indirect/reference variables.

As an example, for this specific case:

echo "${!threshold}"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
-1

Use eval command :

eval echo \${$threshold}

More details about this command can be found here:

eval command in Bash and its typical uses

Community
  • 1
  • 1
RBH
  • 572
  • 4
  • 11
  • 1
    Boo, hiss -- `eval` introduces room for bugs (including security bugs), which more conventional indirection approaches would not. See BashFAQ #48: http://mywiki.wooledge.org/BashFAQ/048 – Charles Duffy Nov 14 '14 at 20:08
  • ...in this specific case -- consider if `threshold` contained, for instance, `'mythreshold:-$(rm -rf /)'`. A safe indirection approach would throw an error or evaluate to an empty string; `eval` would erase your drive. – Charles Duffy Nov 14 '14 at 20:09
  • Downvoting for recommending `eval` to accomplish a task for which `bash` provides explicit support. – chepner Nov 14 '14 at 20:25