georgem
georgem

Reputation: 53

How to echo (print) the value of a variable in Bash?

I am trying to write a little script, and I can not figure out how to choose the variable to be echo'ed (echo $'TEST'_"$response") dynamically depending on the user's input:

#!/usr/bin/env sh

response=response
TEST_1="Hi from 1!"
TEST_2="Hi from 2!"

while [ $response ]; do
  read -p "Enter a choice between 1 - 2, or 'bye': " response
  if [ $response = 'bye' ]; then
  echo "See You !"; exit
  elif [ $response -ge 1 ] && [ $response -le 2 ]; then
       echo $'TEST'_"$response"
  else
    echo "Input is not a valid value."
  fi
done

The desired output would be the value of one of the variables declared at the beginning of my script ("Hi from 1!" or "Hi from 2!"). Instead my script simple outputs the name of the variable as a string "TEST_1" or "TEST_2". I do not simply want to hardcode the variable that will be printed like:

if [ $response -ge 1 ]; then
  echo $TEST_1
fi

since it is not scalable. Using backticks like

echo `$'TEST'_"$response"`

doesn't help either since bash will expect to run the result "TEST_1" or "TEST_2" as a command.

Any hint will be greatly appreciated.

Upvotes: 4

Views: 28978

Answers (2)

user2953222
user2953222

Reputation:

Always use quotes, such as "$string", for anything other than numbers. For numbers, just keep it normal (i.e. $number).

Upvotes: 0

fedorqui
fedorqui

Reputation: 289555

You need indirect expansion, to be used with ${!var}:

$ TEST1="hello"
$ TEST2="bye"
$ v=1
$ var="TEST$v"   #prepare the variable name of variable
$ echo ${!var}   #interpret it
hello
$ v=2
$ var="TEST$v"   #the same with v=2
$ echo ${!var}
bye

That is, you need to use a variable name of a variable and this is done with the indirect expansion: you use a variable with the name of the variable and then you evaluate it with the ${!var} syntax.

In your case, use:

myvar="TEST$response"
echo "${!myvar}"

Upvotes: 2

Related Questions