Hello, my problem is simple & I searched a lot but I couldn't find anything about it:
Basically I'd like to pass $i to a variable, $i being the positional variable; but it is unknown in the beginning so I can't do it like eg. myvar=$3, it HAS to be the "i"..
First, I tried myvar=$($i) (because $i is the number of i (ex 5), and not the positional variable ($5) so we would need in theory another $ to get to the positional variable), doesn't work
I tried this also, though I'm not sure if it's correct:
myvar=${!($[2+$a])}
(in my code, i'd like myvar to get the (2+$a) number for the positional variable).
It's best to avoid eval if at all possible. If you don't consider its implications very carefully, it can be used to inject arbitrary code inside your program.
You can't directly substitute into a variable name like that, no, but if you're willing to do it in two steps, this will work in BASH or new KSH:
Thanks for the replies; I'll try the ideas tonight..
With arrays it's doable (I thought of that too), but it complicates the code since I only need to do it for 2 parameters. I didn't know about eval, but in any case Coronas' seems to be the most simple, so is this code correct like this?
For anyone reading Corona's code and not knowing bash's
${!pattern}
:
${!N} uses the ! pattern matching operator that expands to any variable with the
same name as the value of the variable, in this case N is 2. So, it finds all environment variables with the name "2", or $2.
Why are you putting 'echo' in there? It's not necessary. I just used 'echo' as an example -- the positional parameter gets fed into echo instead of the number itself.
When I say $((N+2)), I don't mean $[$N+2], I mean $((N+2)). I would do what I posted, word for word, letter for letter, keystroke for keystroke.
N=$((2+i))
y=${!N}
I've never heard of that shell syntax before.
BASH seems to accept it, but KSH doesn't:
$ A=1
$ echo $[2+$A]
[2+1]
$
$(( )) works fine in both. So $(( )) is better for portable code.