Timon Tigerli
Timon Tigerli

Reputation: 45

BASH variable values as new defined variables

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?

Upvotes: 0

Views: 76

Answers (2)

chepner
chepner

Reputation: 531055

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"

Upvotes: 1

choroba
choroba

Reputation: 241828

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.

Upvotes: 2

Related Questions