Problem with positional variables in BASH

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).

Thanks for any help, good day

You could use eval. For example:

# cat x.sh
#!/bin/ksh
z=1
x=$(( $z + 2 ))
y=$(eval echo \${${x}})
echo $y
# ./x.sh 1111 2222 3333
3333
1 Like

or array (bash example)

#!/bin/bash
#example usage:  ./thisfile.shl 1 2 3
echo "Parameters are $@"
declare -a parms=("$@")
i=2
echo ${parms}



1 Like

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:

N=$((2+A))
echo "${!N}"
2 Likes

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?

y=$[2+$i]
myval="${!y}"

..or do I need a $ for y? like :

myval="${!$y}"

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.

2 Likes

Neither's correct, actually. The example as I gave it is the version you need to use.

So this should be correct:

N=$[2+i]
y=echo "${!N}"

Also, about:

N=$[2+i]

Shouldn't it be

$[2+$i]?

Thanks

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.

1 Like