0

I'm having a small problem with bash shell script on assigning the values from command line to the arrays. For Example if i type $./test.sh aa bb cc i want the values to be assigned to arrays E.g

test[0]=aa
test[1]=bb
test[2]=cc

and it should be limitless, it has to create arrays according to user input.

This is my code

Thank You

#!/usr/bin/bash
count2=1
declare -a mvne $count2
while [ $# -gt $count2 ]
do
mvne[$count2]=$"[$count2]"  <---here is the problem, how do i assign the command line parameter to the array

echo ${mvne[$count2]}
count2=`expr $count2 + 1`
done   
vahid abdi
  • 9,636
  • 4
  • 29
  • 35
User420
  • 137
  • 3
  • 12

1 Answers1

0

The positional parameters are already array-like. You can assign them to another array without looping:

#!/bin/bash
count2=0
declare -a mvne
mvne=( "$@" )
while [ $# -gt $count2 ]
do
    echo $count2: ${mvne[$count2]}
    ((count2++))
done

When run on a command line:

$ bash test.sh aa bb cc
0: aa
1: bb
2: cc
John1024
  • 109,961
  • 14
  • 137
  • 171
  • `$@` isn't an array, but it is similar to one. You can't index it, for example (`${@[0]}` produces an error; use `$1` instead). While arrays are absent from the POSIX standard and implemented as an extension by various shells, `$@` is a standard special parameter with special expansion behavior when quoted. – chepner Feb 25 '14 at 12:56
  • @chepner OK, yes, answer updated, but I think the analogy is closer than that: one can think of positional parameters as like-an-array but _unnamed_. Being unnamed makes the syntax different. Consequently, the analog for `$@` is not `$name` but `${name[@]}` just as the analog for `$*` is `${name[*]}` and, allowing for different index-origin conventions, the analog for `$1` is `${name[0]}`. – John1024 Feb 25 '14 at 19:09