KSH script arguments

Brad Appleton brad at SSD.CSD.HARRIS.COM
Fri Aug 31 00:09:36 AEST 1990


In article <858 at iiasa.UUCP> wnp at iiasa.UUCP (wolf paul) writes:
>In article <b4CC02oVc3Jx01 at amdahl.uts.amdahl.com> jonc at amdahl.uts.amdahl.com (Jonathan Chang) writes:
>)How can I extract the last argument to a ksh script?
>)
>)P.S. Just to add to the challenge, the number of arguments is variable.
>
>This works; whether it is the most elegant solution I don't know:
>
>	LASTARG=$(eval "echo \$$#")
>
>Anyone know of a better way?
>

Actually - this might NOT work properly if the last argument contains a newline
(it will be clobbered) or backslashes that get interpreted by echo (or print).
In any case, you should probably use \${$#} instead of \$$#. A "safer" but
not necessarily better way is to use an array (assuming your version of ksh
does not clobber $* when set -A is used):

set -A argv "$@"    ## dump positional parameters into an array

	## index the last element in the array
    ## this is supremely ugly - even more so since
    ## ${#argv[@]} returns the number of array elements
    ## but the array is 0-based
typeset lastarg=${argv[${#argv[@]}-1]}


from here on in you can use ${argv[i]} instead of $i and 
${argv[*]} (${argv[@]}) in place of $* ($@).

Im still hoping for a better way though! One of the few things I 
like that csh has over ksh, is being able to returns subsets of
an array (a la $argv[5-8], $argv[-3], $argv[4-]) but I still dont
think csh had an "easy" way of getting just the last argument.

______________________ "And miles to go before I sleep." ______________________
 Brad Appleton        brad at travis.ssd.csd.harris.com   Harris Computer Systems
                          ...!uunet!hcx1!brad          Fort Lauderdale, FL USA
~~~~~~~~~~~~~~~~~~~~ Disclaimer: I said it, not my company! ~~~~~~~~~~~~~~~~~~~



More information about the Comp.unix.questions mailing list