Stony
Stony

Reputation: 3624

How to assemble variable by string

I have the following shell script, let's say its' name test.sh

#!/bin/bash
b_x='it is the value of bx'
c_x='it is the value of cx'

case "$1" in
    "b")
       echo $1_x    # it's doesn't work; I want to echo $b_x
       ;;
     "c")
       echo $1_x   # it's doesn't work; I want to echo $c_x
       ;;
esac

And then I want to call the script;

./test.sh  b    # I want the output is "it is the value of bx"
./test.sh  c    # I want the output is "it is the value of cx"

Upvotes: 0

Views: 54

Answers (2)

ghoti
ghoti

Reputation: 46836

You're asking how to use a variable to name a variable. The standard POSIX method would be to use eval.

$ a_x="Hello world"
$ foo="a"
$ eval echo "\$${foo}_x"
Hello world

Note the escaped dollar sign, which is used to expand the evaluated variable caused by expanding the first variable.

Most folks will tell you that you probably shouldn't use eval, it's dangerous and unruly. I will also tell you this, though there are cases where eval does exactly what you need and you can control its input.

Instead, bash offers something called "indirection" (which you can search for in man bash). You use it like this:

$ a_x="Hello world"
$ foo=a
$ bar="${foo}_x"
$ echo "${!bar}"
Hello world

Note the extra variable.

Upvotes: 0

anubhava
anubhava

Reputation: 785068

You don't need case. Just use indirect variable name expansion:

b_x='it is the value of bx'
c_x='it is the value of cx'

var="${1}_x"
echo "${!var}"

Then run it as:

$> bash test.sh b
it is the value of bx

$> bash test.sh c
it is the value of cx

Upvotes: 3

Related Questions