|
|
|
|
||||||
| comp.unix.shell Using and programming the Unix shell. |
![]() |
|
|
LinkBack | Outils de la discussion |
|
|
#1 |
|
Messages: n/a
Hébergeur: |
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 |
|
|
|
#2 |
|
Messages: n/a
Hébergeur: |
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 ${!#} |
|
|
|
#3 |
|
Messages: n/a
Hébergeur: |
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. |
|
|
|
#4 |
|
Messages: n/a
Hébergeur: |
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 |
|
|
|
#5 |
|
Messages: n/a
Hébergeur: |
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 > |
|
|
|
#6 |
|
Messages: n/a
Hébergeur: |
Yakov <iler...@gmail.com> 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 |
|
![]() |
| Outils de la discussion | |
|
|