Extracting unknown positional parameter in Bourne shell

I have a variable that contains the number of a positional parameter. There is no way of knowing what number this may be, although it is guaranteed to correspond with a valid parameter.

In BASH I could just use ${@[$var]} to extract that argument. But in a Bourne shell the best I can come up with is to use a for-loop with a counter as in this sample script (where the first parameter is the position to extract from those that follow):

#!/bin/sh

[ ${#@} -lt 2 ] && exit

x=$1
shift

i=1
for v in $@; do
   [ $i = $x ] && echo $v
   i=$(( i + 1 ))
done

Is there any easier way to do this?

Thanks.

Try:

eval v=\${$x}
echo "$v"
1 Like

I always forget about eval, too much time spent in other languages where similar functions are only desperate last resorts.

That worked perfectly, thanks.

You're welcome. Yes, also in Shell one should think twice before using eval in certain situations, so that it does not leave a security hole. Those curly brackets are important in this case BTW. If you leave them out then if the parameter would become $10 for example, that would get evaluated to $1 with a trailing zero, whereas ${10} would give the right result.