0

I have a shell script like this,

#!/bin/bash
foxy1="foxyserver"
H="1"

and the output should be foxyserver.

I tried this,

echo $foxy$H

and this gives me

1

and then I used

str="foxy$H"
echo $str

the output is

foxy1

How could I do that?

2 Answers 2

6

Use indirect variables, as described in BashFAQ #6:

$ foxy1="foxyserver"
$ H="1"
$ varname="foxy$H"
$ echo "${!varname}"
foxyserver
Sign up to request clarification or add additional context in comments.

Comments

2

Using eval, you can do indirection:

eval echo \$$str

Output

foxyserver

Warning: This is not really good practice. For example, if you have str=(rm -rf ~/*) then the eval expression would be $(rm -rf ~/*). So be warned and use indirection as suggested by Charles Duffy.

1 Comment

From a security perspective, this is bad practice. Indirect variables would only let you name a variable to be expanded, whereas eval lets your variables' contents do literally anything.

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.