pankaj
pankaj

Reputation: 11

BASH SCRIPT : How to use a variable inside another variable

I need to store command line arguments passed in an array

my Command is

./test1.sh 2 4 6

Now i need to store 2 4 6 in an array and im using..

s1=$#     
"it tells how many arguments are passed."


for (( c=1; c<=$s1; c++ ))

do

     a[$c]}=${$c}

I have written ${$c} for taking the arguments value but it is showing bad substition.

Upvotes: 1

Views: 223

Answers (3)

Zskdan
Zskdan

Reputation: 819

bash variable can be indirectly referenced by \$$VARNAME or by ${!VARNAME} in version 2 so your assignment statement must be :

a[$c]=${!c} 

or

eval a[$c]=\$$c

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96258

You can always pick the first argument and drop it. Use $1 and shift.

c=1
while [ $# -gt 0 ]; do
    a[$c]=$1
    c=$((c+1))
    shift
done

Upvotes: 0

johangu
johangu

Reputation: 824

This will give you an array with the arguments: args=("$@")

And you can call them like this: echo ${args[0]} ${args[1]} ${args[2]}

Upvotes: 7

Related Questions