BladeSystem Forums have moved here
To make BladeSystem information easier to find, we have moved the BladeSystem forums here, to Servers and Operating Systems.
Showing results for 
Search instead for 
Do you mean 

nested variable access

nested variable access

I am trying to write a shell script, which will print the 1st or 2nd or 3rd commanline argument values based on the value contained in a variable (say i=1 or 2 or 3 respectively)

i=2
echo \$$i

I tried different options like \$$i, ${$i}, $'$i', $"$i" etc. but nothing is working out.

Please help me do this.
7 REPLIES
Honored Contributor

Re: nested variable access

HI,
have you looked at using shift within a loop ?

"PSEUDO CODE" !
a=0
b=$1
while $a < $b
do
shift
a=a+1
done
echo $1
Honored Contributor

Re: nested variable access

Hi,

I'd use an array:

set -A args "$@"

echo ${args[$var]}
Decay is inherent in all compounded things. Strive on with diligence
Honored Contributor

Re: nested variable access

Another option:

#!/usr/bin/sh
echo $*| awk -F' ' '{print $$1};'
Honored Contributor

Re: nested variable access

Hello,

#!/usr/bin/sh
set -A a "${@}"
i=2
echo "${a[${i}]}"
exit

Note that array indexing starts at 0.

PCS
Honored Contributor

Re: nested variable access

all of those will work a case statement would work also.

case $i in
1)
echo $1
;;
2)
echo $2
;;
3)
echo $3
;;
esac

However personally I always use getopts to process commandline argument values.

while getopts a:ishv: opt
do
case ${opt} in
a) VGM=${OPTARG}
;;
i) opt_i=true
;;
s) opt_s=true
;;
v) VG=${OPTARG}
;;
h|*) usage ${0##*/}
;;
esac
done
Honored Contributor

Re: nested variable access

Put the following code in your script:

#!/bin/sh
i=2
eval echo \$$i

Re: nested variable access

The replies were highly useful.