Simpler Navigation coming for Servers and Operating Systems
Coming soon: a much simpler Servers and Operating Systems section of the Community. We will combine many of the older boards, and you won't have to click through so many levels to get at the information you need. If you are looking for an older board and do not find it, check the consolidated boards, as the posts are still there.
cancel
Showing results for 
Search instead for 
Did you mean: 

nested variable access

Highlighted

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
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

Re: nested variable access

The replies were highly useful.