Results 1 to 7 of 7
Hello,
I need help with dynamic variable which get number and string from array.
Code:
_0_USERS=(11 taaa 15 20 22)
grupa=0
for ((n=0; n<3;n=$[n+1]));do
echo "
$[_${grupa}_USERS[$n]]
_${grupa}_USERS[$n]"
done
Resault ...
- 11-15-2007 #1Just Joined!
- Join Date
- Nov 2007
- Posts
- 3
[BASH] Arrays and dynamic variable
Hello,
I need help with dynamic variable which get number and string from array.
Resault is:Code:_0_USERS=(11 taaa 15 20 22) grupa=0 for ((n=0; n<3;n=$[n+1]));do echo " $[_${grupa}_USERS[$n]] _${grupa}_USERS[$n]" done
As you can see, everything is ok until it meet a string than it put 0 instead "taaa". If i put only strings into array still get 0sCode:11 _0_USERS[0] 0 _0_USERS[1] 15 _0_USERS[2]
- 11-15-2007 #2
$[_${grupa}_USERS[$n]]
For some reason, that can't be evaluated into a string. I've never used brackets like this, so I am not too sure why. Honestly, this code is awful looking, and you should re think the way you're doing things. What exactly are you trying to accomplish?
- 11-15-2007 #3
I agree with likwid that this script is very poor-looking. It can probably be written better.
In any event, the problem here is that $[...] notation invokes arithmetic mode. Strings become 0 in arithmetic mode, hence the 0. What you actually want is something like:
(that is, ${...} syntax instead).Code:${_0_$grupa_USERS[$n]}DISTRO=Arch
Registered Linux User #388732
- 11-15-2007 #4Just Joined!
- Join Date
- Nov 2007
- Posts
- 3
./a: line 4: ${_0_$grupa_USERS[$n]}: bad substitution
This is only an example of problem. I dont care about "looking", i just want it to work. Now i had to refer to another array with names and that works_0_USERS=(11 u 15 20 22)
grupa=0
for ((n=0; n<3;n=$[n+1]));do
echo ${_0_$grupa_USERS[$n]}
done
- 11-15-2007 #5Linux User
- Join Date
- Jun 2007
- Posts
- 318
You need to use the eval command:
VicCode:eval echo \${_${grupa}_USERS[$n]}
- 11-15-2007 #6
You will care about how it looks when you go back in a year to add/tweak some code.
I suggest thinking about the problem to see if you can avoid this situation. There are lots of roads to the same point, some shorter, and less windy than others.
- 11-16-2007 #7Just Joined!
- Join Date
- Nov 2007
- Posts
- 3


Reply With Quote
