• 0

[UNIX] Declaring var using another var in its name


Question

For some strange reason syntax such as:

anotherVar=1

Name$anotherVar=" 0"

Gives me: Name1= 0 : Command not found

I have used a similar declaration with "read -p" and it didn't complain.

Ideas?

Edited by Zapadlo
Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

I assume you're doing sh given the unix in the title. What you're doing looks really wierd. Dynamically naming variables is something you don't see in many languages (none come immedietly to mind) and I'm sure sh doesn't do it. You've probably seen it used in some string context where it's doing substitution such as:

foo=5
echo "bar$foo"

Link to comment
Share on other sites

  • 0

If you're gonna end up with lots of variables named name1, name2, name3 etc etc then just use an array.

But yeah, dynamically naming variables is a bit iffy.

Link to comment
Share on other sites

  • 0
Thank you for the replies, got it working with eval:

eval Var$z=\"o\"

Wow, I didn't know you could do that. It's a bit strange. Just out of curiosity, what's your reason for using such code?

Link to comment
Share on other sites

  • 0

If i would have seen this topic earlier I would have mentioned the eval way. It's useful where you have variables like $user1_score, $user2_score etc and you have a function where to work with the variables. Simply call the function with 'user1', 'user2' etc and it'll use the correct variables.

One word of warning, make sure you know what the variables contain!

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.