get arguments passed and put it in an array

15,182

Solution 1

They are already in an array, the array of positional parameters $@ with individual elements accessed with $1, $2... (start at 1, $0 is the script name).

Note that there are several implementations (and versions thereof) of ksh: AT&T ksh88 (as found in most commercial Unices), AT&T ksh93 (made open source in 2000, sometimes found as dtksh on commercial Unices and as an optional package on opensource unix-likes), pdksh and its derivatives (MirBSD ksh, OpenBSD ksh) which was the only ksh available on opensource Unix-likes before 2000 and zsh (when called as ksh).

To assign to another array, with ksh88 (also works with all other implementations of ksh except older pdksh):

set -A array -- "$@"

With older versions of pdksh:

set -A array "$@"

With ksh93, zsh and recent versions of mksh:

array=("$@")

Solution 2

$ cat t.ksh
#!/bin/ksh

element=( "$@" )

echo "${element[0]}"
echo "${element[1]}"
echo "${element[2]}"

.

$ ./t.ksh one two three
one
two
three

Although I don't understand why you would want to do that, the positional parameters are readily available in $@ which you can easily iterate over.

Share:
15,182

Related videos on Youtube

kickass00
Author by

kickass00

Updated on September 18, 2022

Comments

  • kickass00
    kickass00 almost 2 years

    is there a way to make the arguments passed become the element of an array?

    I want to access those arguments individually through array.

    like this:

    ./script.ksh arg1 arg2 arg3
    

    then it will become like this:

    element[0]=arg1
    element[1]=arg2
    element[2]=arg3
    
    • Stéphane Chazelas
      Stéphane Chazelas over 10 years
      You know they are already in $1, $2..., right?
  • mirabilos
    mirabilos about 10 years
    The =(…) syntax is supported in no pdksh version, only mksh. (And the original AT&T Korn Shell, of course.)
  • Stéphane Chazelas
    Stéphane Chazelas about 10 years
    @mirabilos Well, that's what I meant by newer pdksh, as mksh is where the development of pdksh variant of ksh is happening. I suppose oksh merges features from mksh as well, doesn't it? If you prefer I make a distinction on the name, or if you have a generic name for the pdksh family of shells, like pdksh and its derivatives, let me know.
  • mirabilos
    mirabilos about 10 years
    No, neither OpenBSD nor Deli Linux merge mksh changes into their oksh flavour generally. The latter tried but violated the licence, so they had to revert that change after I pointed that out to them. (As a European Citizen, I have to choose a proper OSS licence for my code.)