2

I have a problem with a bash script.

I would like to insert a variable into another variable in a bash script, but the risult is not what I should expect.

Here the code

input1="inputnumber1"
input2="inputnumber2"
input3="inputnumber3"
dummy="input"
for i in $(seq 1 3)
do
    toprint=$dummy$i
    echo "$toprint"
done

I would expect this code print the content of the variable $input1, $input2 and $input3, but it just print input1, input2 and input3.

Any suggestion?

Thanks in advance.

1
  • 1
    Use {1..3} instead of seq Commented Sep 17, 2013 at 13:54

3 Answers 3

3

Use an indirect variable reference:

varname="$dummy$i"
toprint="${!varname}"
Sign up to request clarification or add additional context in comments.

Comments

2

Say:

echo "${!toprint}";

Also read this. You can also read about indirect expansion in the manual.

Comments

1

Try the eval command:

eval toprint='$'$dummy$i
echo $toprint

More on eval on unix.stackexchange.com

1 Comment

That's a nice one too!

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.