Zsh: access the last command line argument assigned by script

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

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

But it seems too opaque.

+6
source share
3 answers

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

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

A method that works in all Bourne-style shells, including zsh,

 eval last=\$$# 

(You were on the right track, but running echo simply pointless to output it.)

+8
source
 last=${@[-1]} 

gotta do the trick. More generally,

 ${@[n]} 

will give * n * th parameter, and

 ${@[-n]} 

will result in the last parameter * n * th.

+8
source

The colon parameter extension is not in POSIX, but it works with at least zsh, bash and ksh:

 ${@:$#} 

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

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

Source: https://habr.com/ru/post/897722/


All Articles