I would like to use a variable as a index value to refer to positional variables passed to script, e.g.:
x=101
y=201
z=301
foo(){
i=0;
(( i+=1 )); # i=1
echo "${$i}"; # parameter 1
(( i+=1 )); # i=2
echo "${$i}"; # parameter 2
(( i+=1 )); # i=3
echo "${$i}"; # parameter 3
}
foo x y z
output:
101
201
301
Arrays and loops will not help in this case, I need a simple method of incrementing a int variable and using this value as a index to retrieve a method parameter passed.
Advice?
I believe you need indirect variable expansion here:
x=101
y=201
z=301
foo() {
local i
local v
for ((i=1; i<=3; i++ )); do
v="${!i}" # will get x, y, z
echo "${!v}" # will get values of $x, $y, $z
done
}
Then call it as:
foo x y z
101
201
301