Hello All,
I'm trying to assign integer values to variables using substitution in both the value and variable's name, i.e.,
number$x=$x
where x is equal to one in the first assignment, two in the second assignment, and so on with x being incremented each time.
However, when I do the first assignment
number$x=$x
the assignment works but I get
number1=1 not found.
what's going on?
Thank you in advance.
Rule: if you compose a string, and you want to run it, and it is other than a command name,then you need eval.
What shell are you using? Does it have arrays:
number[x]=$x
echo "${number[x]}"
Yes, I see that the eval command works.
However, the assignment also does work without eval.
But, I get that "not found" error.
What's going on there?
Without eval
the shell is trying to execute the command number1=1
which apparently is not present on your system so it says "not found"
Obviously.
But why is the shell trying to execute a command?
Why is not performing assignment?
So, I'll ask once again, what's going on here?
That is because the shell parses in a certain order and the phase where it recognizes an assignment is before the expansion of the variables. So in this phase the variable $x is not yet expanded, so the simple command that would constitute an assignment is not recognized since the "variable" contains a dollar sign which is not a valid character for a variable.
With eval
this phase is visited after the variable $x will have been expanded, so then it will be recognized and parsed as such.
Shell Command Language: Introduction