Create array with arguments passed to the script

Hi guys, I have to create an array with the arguments passed to the script .... I thought of something like that ...

for X in seq 1 $# ;

do 
            arr[X]=$X

done 

but if I go to print for example arr [1] I print 1 and not the name of the argument...
can someone help me please?

It doesn't work that way. First, you need to use a "command substitution" for the seq command. Then, $X will be expanded to 1 .. $#, NOT to the values of the respective positional parameters. There are other ways:

for X in $(seq 1 $#)
  do    arr[X]=$1
        shift
  done

or

arr=($@)

which will assign elements starting from 0, or, less favoured, using the deprecated (and dangerous) eval ,

for X in $(seq 1 $#)
  do     eval arr[X]=\$$X
  done
4 Likes
arr=("$@")

Quotes around $@ (and ${arr[@]} ) protect against word splitting and other substitutions, but still retain the list of argument members (and other array members).

In contrast, with $* and ${arr[*]} the quotes would enforce one string.

4 Likes