0

I don't know exactly how to ask this in English, but I want to have the value of a variable as a new variable... The script also has a loop with increasing numbers, and in the end I want to have the variables VAR1, VAR2 etc.

I'm trying this:

COUNT=$(echo 1)
DEFINE=$(echo VAR$COUNT)
$DEFINE=$(echo gotcha!)

When I try this way, I have this error message:

~/script.sh: line n: VAR1=gotcha!: command not found

I played a bit around with brackets and quotation marks, but it didn't work... any solutions?

2
  • The question is tagged with bash. Why aren't you instead using bash arrays? Commented Oct 31, 2014 at 18:04
  • Why are you using echo in a command substitution? this is really silly. Use this instead: count=1, define=var$count. Now for the last one, you may use printf -v "$define" '%s' 'gotcha!'. Commented Oct 31, 2014 at 18:06

2 Answers 2

2

The problem is that bash expects a command as a result of expansions, not an assignment. VAR1=gotcha! is not a command, hence the error.

It would be better to use an array:

COUNT=$(echo 1)
VAR[COUNT]='gotcha!'
echo ${VAR[COUNT]}

I guess $(echo 1) stands for a more complex command, otherwise you can just use COUNT=1.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use declare to create such a "dynamic" variable, but using an array is probably a better choice.

COUNT=1
DEFINE="VAR$COUNT"
declare "$DEFINE=gotcha"

1 Comment

Thank you. This solved my SPECIFIC problem completely. Also thanks to all other contributors. As a neophyte, i'm surely gonna fall in love with StackOverflow ^^.

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.