6

I want to get the last element of $*. The best I've found so far is:

 last=`eval "echo \\\$$#"`

But that seems overly opaque.

3 Answers 3

11

In zsh, you can either use the P parameter expansion flag or treat @ as an array containing the positional parameters:

last=${(P)#}
last=${@[$#]}

A way that works in all Bourne-style shells including zsh is

eval last=\$$#

(You were on the right track, but running echo just to get its output is pointless.)

9
last=${@[-1]}

should do the trick. More generally,

${@[n]}

will yield the *n*th parameter, while

${@[-n]}

will yield the *n*th to last parameter.

0

The colon parameter expansion is not in POSIX, but this works in at least zsh, bash, and ksh:

${@:$#}

When there are no arguments, ${@:$#} is treated as $0 in zsh and ksh but as empty in bash:

$ zsh -c 'echo ${@:$#}'
zsh
$ ksh -c 'echo ${@:$#}'
ksh
$ bash -c 'echo ${@:$#}'

$

Not the answer you're looking for? Browse other questions tagged or ask your own question.