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

2 Answers 2

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}"
Sign up to request clarification or add additional context in comments.

Comments

-1

Use eval command :

eval echo \${$threshold}

More details about this command can be found here:

eval command in Bash and its typical uses

3 Comments

Boo, hiss -- eval introduces room for bugs (including security bugs), which more conventional indirection approaches would not. See BashFAQ #48: mywiki.wooledge.org/BashFAQ/048
...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.
Downvoting for recommending eval to accomplish a task for which bash provides explicit support.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.