[bash] last element of the $* array
am 01.11.2007 00:30:36 von Yakov
How do I refer to the last element of args array
(the $* array) in bash ?
For example: set -- a b c; echo ${...} ... I want 'c' printed here.
I tried ${*[-1]}, bash refuses to read my mind.
Thanks
Yakov
Re: [bash] last element of the $* array
am 01.11.2007 00:52:51 von wayne
Yakov wrote:
> How do I refer to the last element of args array
> (the $* array) in bash ?
>
> For example: set -- a b c; echo ${...} ... I want 'c' printed here.
> I tried ${*[-1]}, bash refuses to read my mind.
>
> Thanks
> Yakov
>
Try:
echo ${!#}
Re: last element of the $* array
am 01.11.2007 05:44:49 von Jstein
Yakov,
The variable $# tells you how many positional parameters exist in $1,
$2, $3, $4 ... $N
Under OLD shells, like the original bourne, you couls only reach $1 to
$9, and all othes
were un-touchable, until you used the "shift" command to get rid of
the first parameters,
and bring the other ones down below position ten. So people used to
write loops like:
while [ $# -gt 0 ]
do
#- process your parameters, using $1 and possibly some $2 or $3
to follow
#- set up various other info
#- perhaps store some of the params of interest
KEEP_PARAMS="$KEEP_PARAMS $1"
shift
#- this discards $1, and shifts $2 into the current $1
done
#- When you were done you could put parts of them back (if you really
wanted) with
set -- $KEEP_PARAMS
#- and the ones you liked would go back into $1, $2 ... $N
Now, several shells will allow you to access the params past $9
directly using notations like ${52}
or, if you lave a counter variable, like HERE, where HERE=52, you
could access that param with
the notation of ${!HERE} (the exclamation point says, use the value
of HERE as a pointer/reference)
That should get you what you need.
Re: [bash] last element of the $* array
am 01.11.2007 10:01:56 von Stephane CHAZELAS
2007-10-31, 23:30(-00), Yakov:
> How do I refer to the last element of args array
> (the $* array) in bash ?
>
> For example: set -- a b c; echo ${...} ... I want 'c' printed here.
> I tried ${*[-1]}, bash refuses to read my mind.
[...]
Bash specific:
last=${!#}
(note how the above nicely conflicts with the ${var#pattern}
which is why it doesn't work in ksh93)
Bash/ksh93 specific:
last=${@: -1}
Zsh equivalents:
last=${(P)#}
last=$@[-1]
POSIXly:
eval "last=\${$#}"
Bourne:
for last do :; done
--
Stéphane
Re: [bash] last element of the $* array
am 01.11.2007 13:38:39 von Janis Papanagnou
Yakov wrote:
> How do I refer to the last element of args array
> (the $* array) in bash ?
Another option...
: "$@"
last=$_
Janis
>
> For example: set -- a b c; echo ${...} ... I want 'c' printed here.
> I tried ${*[-1]}, bash refuses to read my mind.
>
> Thanks
> Yakov
>
Re: last element of the $* array
am 02.11.2007 22:35:35 von brian_hiles
Yakov wrote:
> How do I refer to the last element of an array?
A portable, robust, and efficient method that has kept
me in good stead for many years:
eval "set X \"\$@\"; shift $#"
=Brian