0
votes

Sorry if the title isn't very clear. So, I'm trying to echo a variable in bash after using read to get a variable ($A in this example) from a user, like so:

foobar="good"
A=bar
B="\$foo$A"
echo $B

But the output of echoing $B is "$foobar", instead of "good", which is what I want it to be. I've tried using eval $B at the end, but it just told me that "good" isn't a command. eval $(echo $B) didn't work either, it also told me that "good" isn't a command. echo $(eval $B) also told me that "good" isn't a command, and also prints an empty line.

To help clarify why I need to do this: foobar is a variable that contains the string "good", and foobaz contains "bad", and I want to let a user choose which string is echoed by typing either "bar" or "baz" while a program runs read A (in this example I just assigned A as bar to make this question more understandable).

If anyone could please tell me how I can make this work, or offer related tips, I'd appreciate it, thanks.

1

1 Answers

2
votes

You're looking for indirect references:

$ foobar="hello"
$ A=bar
$ B="foo$A"
$ echo "$B" "${!B}"
foobar hello

You should take a look at the How can I use variable variables FAQ for more information about those (and associative arrays).