Operating System - Linux
1752584 Members
4457 Online
108788 Solutions
New Discussion юеВ

Re: nested variable access

 
devhariprasad
Advisor

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 7
Peter Godron
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
Jonathan Fife
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
Peter Godron
Honored Contributor

Re: nested variable access

Another option:

#!/usr/bin/sh
echo $*| awk -F' ' '{print $$1};'
spex
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
Marvin Strong
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
Sandman!
Honored Contributor

Re: nested variable access

Put the following code in your script:

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

Re: nested variable access

The replies were highly useful.