get arguments passed and put it in an array
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.
Related videos on Youtube
kickass00
Updated on September 18, 2022Comments
-
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 over 10 yearsYou know they are already in
$1
,$2
..., right?
-
-
mirabilos about 10 yearsThe
=(…)
syntax is supported in nopdksh
version, onlymksh
. (And the original AT&T Korn Shell, of course.) -
Stéphane Chazelas about 10 years@mirabilos Well, that's what I meant by newer
pdksh
, asmksh
is where the development ofpdksh
variant ofksh
is happening. I supposeoksh
merges features frommksh
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, likepdksh
and its derivatives, let me know. -
mirabilos about 10 yearsNo, 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.)