nested variable access (252 Views)
Reply
Advisor
devhariprasad
Posts: 43
Registered: ‎08-28-2006
Message 1 of 8 (252 Views)

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.
Honored Contributor
Peter Godron
Posts: 4,470
Registered: ‎02-13-2002
Message 2 of 8 (252 Views)

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
Jonathan Fife
Posts: 256
Registered: ‎07-19-2006
Message 3 of 8 (252 Views)

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
Peter Godron
Posts: 4,470
Registered: ‎02-13-2002
Message 4 of 8 (252 Views)

Re: nested variable access

Another option:

#!/usr/bin/sh
echo $*| awk -F' ' '{print $$1};'
Honored Contributor
spex
Posts: 1,367
Registered: ‎05-14-1996
Message 5 of 8 (252 Views)

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
Marvin Strong
Posts: 492
Registered: ‎03-01-2004
Message 6 of 8 (252 Views)

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
Sandman!
Posts: 2,220
Registered: ‎01-13-2005
Message 7 of 8 (252 Views)

Re: nested variable access

Put the following code in your script:

#!/bin/sh
i=2
eval echo \$$i
Advisor
devhariprasad
Posts: 43
Registered: ‎08-28-2006
Message 8 of 8 (252 Views)

Re: nested variable access

The replies were highly useful.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.