rampion
rampion

Reputation: 89063

zsh: access last command line argument given to a script

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

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

But that seems overly opaque.

Upvotes: 6

Views: 3573

Answers (3)

nisetama
nisetama

Reputation: 8863

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 ${@:$#}'

$

Upvotes: 0

Ian Robertson
Ian Robertson

Reputation: 1348

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.

Upvotes: 9

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.)

Upvotes: 11

Related Questions